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

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

问题描述

我想要的文件myfile.txt的内容追加到在C第二个文件myfile2.txt的结束。我可以复制的内容,但我不能找到一个方法来添加。这里是我的code:

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?

推荐答案

打开追加:

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

然后就写 pFile2 ,无需 fseek的()

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

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