C语言 追加到 C 中的文件末尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19429138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:43:56  来源:igfitidea点击:

Append to the end of a file in C

cfileappendfseek

提问by Sonofblip

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:

我试图将文件 myfile.txt 的内容附加到 c 中第二个文件 myfile2.txt 的末尾。我可以复制内容,但找不到追加的方法。这是我的代码:

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?

我认为我没有正确使用 fseek,但我想要做的是调用 fseek 将指针放在文件的末尾,然后在该指针的位置写入,而不是在文件的开头文件。这是正确的方法吗?

回答by cdarke

Open with append:

用追加打开:

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

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

然后直接写信pFile2,没必要fseek()

回答by Sergey L.

Following the documentation of fopen:

遵循以下文档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.

``a'' 开放写作。如果文件不存在,则创建该文件。流位于文件的末尾。对文件的后续写入将始终在文件的当前结尾处结束,而不管中间有任何 fseek(3) 或类似操作。

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

因此,如果您pFile2=fopen("myfile2.txt", "a");将流定位在末尾以自动追加。做就是了:

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