Is there an easy way to append the contents of one file to another?
Currently, I have to do the following steps explicitly:
1) Read all data from file A into RAM (fopen, fseek, fread)
2) Write all data to file B (fwrite).
Is there a built-in way of doing this? As I understand it, 'memcpy'
only copies blocks of memory from one part of RAM to another, not
between files.
Assuming text input files, with no line longer than one million
characters, something along these lines should work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static char string[1000000];
void catstrings(FILE * in, FILE * out)
{
setvbuf(in, NULL, _IOFBF, 1024 * 16);
setvbuf(out, NULL, _IOFBF, 1024 * 16);
while (fgets(string, sizeof string, in)) {
fputs(string, out);
}
}
int main(int argc, char **argv)
{
FILE *in = stdin;
FILE *out = stdout;
clock_t start,
end;
static const double cps = 1.0 / CLOCKS_PER_SEC;
if (argc > 1) {
in = fopen(argv[1], "r");
if (in == NULL) {
printf("Error opening %s\n", argv[1]);
exit(EXIT_FAILURE);
}
}
if (argc > 2) {
out = fopen(argv[2], "a");
if (out == NULL) {
printf("Error opening %s\n", argv[2]);
exit(EXIT_FAILURE);
}
}
start = clock();
catstrings(in, out);
end = clock();
printf("big buffer cat using fgets took %f seconds\n", (end -
start) * cps);
fflush(NULL);
return 0;
}
/*
W:\tmp>dir bible.txt
Volume in drive W has no label.
Volume Serial Number is 0890-87CA
Directory of W:\tmp
03/25/2008 08:15 PM 4,047,392 bible.txt
1 File(s) 4,047,392 bytes
0 Dir(s) 64,396,148,736 bytes free
W:\tmp>fatcat bible.txt b.txt
big buffer cat using fgets took 0.535000 seconds
W:\tmp>dir b.txt
Volume in drive W has no label.
Volume Serial Number is 0890-87CA
Directory of W:\tmp
06/22/2009 09:08 PM 4,077,775 b.txt
1 File(s) 4,077,775 bytes
0 Dir(s) 64,392,069,120 bytes free
W:\tmp>fatcat bible.txt b.txt
big buffer cat using fgets took 0.470000 seconds
W:\tmp>dir b.txt
Volume in drive W has no label.
Volume Serial Number is 0890-87CA
Directory of W:\tmp
06/22/2009 09:08 PM 8,155,550 b.txt
1 File(s) 8,155,550 bytes
0 Dir(s) 64,387,989,504 bytes free
W:\tmp>fatcat bible.txt b.txt
big buffer cat using fgets took 0.478000 seconds
W:\tmp>dir b.txt
Volume in drive W has no label.
Volume Serial Number is 0890-87CA
Directory of W:\tmp
06/22/2009 09:08 PM 12,233,325 b.txt
1 File(s) 12,233,325 bytes
0 Dir(s) 64,383,913,984 bytes free
*/