user923005 <> writes:
> On Jun 22, 6:41*pm, Ishmael <stahl.k...@gmail.com> wrote:
>> 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);
Why 16 kilobytes in partiuclar?
> while (fgets(string, sizeof string, in)) {
> fputs(string, out);
> }
> }
[snip]
That will work equally well with lines longer than one million
characters; long lines will simply be processed in two or more chunks.
Which raises the question of why you need such a big buffer anyway, or
why you'd use fgets and fputs rather than fread and fwrite.
For that matter, you could just use fgetc and fputc and copy one
character at a time. Both are normally defined as macros that will
buffers of whatever size makes sense for the system. In fact, it
would be interesting to write two versions of the program, one that
uses fgetc and fputc, and another than copies, say, 16 kbytes as a
time, and compare their performance.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"