这里我有一个文件名,我想先创建这个文件。
我想在文件中留下一些字节,然后再写入数据。
所以在下面的代码中我使用了fseek(pFile, 10, SEEK_SET)
。
比我在这里从第 11 个位置开始在文件中写“sam”
。
然后关闭文件并再次以追加模式打开该文件 4 次,并在文件末尾写入“abc”
。
因此 example.txt
中的总字节数为 25
字节。
所以文件数据就像这样.........samabcabcabcabc
。
但我不想在这个文件数据中包含“sam”。意味着我只需要 22 个字节。
如果我在这里不使用 fputs("sam", pFile);
,那么它只提供 12 个字节,文件数据看起来像 abcabcabcabc
。
我想要在像 .........abcabcabcabc
这样的文件中输出。
在实际程序中,我有一个函数在 10 个字节后 append 数据。并且这个函数被多次调用,那么我怎样才能实现这个目标呢?
我的示例代码在这里。
#include <stdio.h>
int main() {
FILE * pFile;
pFile = fopen("example.txt", "wb");
fseek(pFile, 10, SEEK_SET);
fputs("sam", pFile);
fclose(pFile);
append("example.txt");
append("example.txt");
append("example.txt");
append("example.txt");
return 0;
}
void append(char *file) {
FILE * pFile;
pFile = fopen("example.txt", "ab");
fputs("abc", pFile);
fclose(pFile);
}
最佳答案
来自man fopen
When you open a file for appending (that is, when the Type parameter is set to a), it is impossible to overwrite information already in the file.
因此,如果您希望像在 append()
中所做的那样以 append 模式打开文件,则无法覆盖 sam
即使在a+
打开模式下,您也可以将内部指针重新定位(使用fseek
、rewind
)到文件中的任何位置进行读取,但写入操作会将其移回文件末尾。
解决方法是第一次使用r+
打开模式,使用fseek
重新定位内部指针,然后写入abc
。之后,您可以照常调用append
关于C文件操作困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9699713/