-
Storng data
I have this code as below for copying the contents of one file to another file. What I want to know is Can I use this code as below to copy the first line of one file and place it in another file, then take the first line of the second file and copy it to "ToFile" so that the data will be stored beside each other. The program must then take the 2nd line for each or the two files and store them on the next line of "ToFile" but beside each other and so on until all the data has been copied from the files.
static void
MyCopyFile(char *FromFile, char *ToFile)
{
FILE *from;
FILE *to;
char FileBuf[256];
if ((from = fopen(FromFile, "r")) != NULL)
{
/* THE "a" WILL APPEND TO THE FILE, IF YOU WANT TO CREATE A NEW FILE, USE "w" */
if ((to = fopen(ToFile, "a")) != NULL)
{
while (fgets(FileBuf, 255, from) != NULL){
char *p = strchr( FileBuf, '\n' );
if ( p ) *p = '\0'; // this removes the newline
strcat( FileBuf, " X X X\n\n" );
fputs(FileBuf, to);
}
fclose(to);
}
else
printf("Cannot open %s\n", ToFile);
fclose(from);
}
else
{
printf("Cannot open %s\n", FromFile);
}
}
-
Read line 1 from file A into a character buffer, then read line 1 from file B into a buffer, use strcat() to append the B buffer to the end of the A buffer and write the combined buffer to your output file. Repeat with line 2...
Depending on what you want to do, the above procedure could be simpler if you are not manipulating the buffers at all, (i.e. you do not actually need 2 buffers, you could build it all in 1).