Append to the end of a file in C

天涯浪子 提交于 2019-12-17 15:46:37

问题


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 code:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", r+);
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(!feof(pFile)) {
        if(fgets(buffer, 100, pFile) != NULL) {
        fseek(pFile2, -100, SEEK_END);
        fprintf(pFile2, buffer);
    }
}
fclose(pFile);
fclose(pFile2);

I don't think I'm using fseek correctly, but what I'm trying to do is call fseek to put the pointer at the end of the file, then write at the location of that pointer, instead of at the beginning of the file. Is this the right approach?


回答1:


Open with append:

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

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




回答2:


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);


来源:https://stackoverflow.com/questions/19429138/append-to-the-end-of-a-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!