Append to the end of a file in C

前端 未结 2 1560
情深已故
情深已故 2020-12-03 01:00

I\'m trying to append the contents of a file myfile.txt to the end of a second file myfile2.txt in c. I can copy the contents, but I can\'t find a way to append. Here\'s my

相关标签:
2条回答
  • 2020-12-03 01:08

    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);
    
    0 讨论(0)
  • 2020-12-03 01:30

    Open with append:

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

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

    0 讨论(0)
提交回复
热议问题