追加到 C 中的文件末尾 [英] Append to the end of a file in C

查看:19
本文介绍了追加到 C 中的文件末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

Open with append:

Open with append:

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

然后直接写入pFile2,不需要fseek().

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

这篇关于追加到 C 中的文件末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆