Append to the end of a file in C Append to the end of a file in C c c

Append to the end of a file in C


Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().


Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;FILE *pFile2;char buffer[256];pFile=fopen("myfile.txt", "r");pFile2=fopen("myfile2.txt", "a");if(pFile==NULL) {    perror("Error opening file.");}else {    while(fgets(buffer, sizeof(buffer), pFile)) {        fprintf(pFile2, "%s", buffer);    }}fclose(pFile);fclose(pFile2);