我正在给一个文件写一些字符串,然后倒带。这个,我在做一个循环。
实际上,它工作得很好,但是在文件的末尾,它复制了最后一个字符串中的一些字符。我该如何处理多余的字符?
所以,我有一个循环,它将字符串写入文件,并在循环结束时每次倒带:
for循环{
fputs(“string1\n”,file);fputs(“string2\n”,file);fputs(“string3\n”,file);fputs(“stringLAST”,file);fseek(file,0,SEEK_SET);}//或倒带(file);得到相同的结果。
结果我的文件看起来像这样:
String1String2String3StringLastStringLastAstStst
现在,我在stringLAST
字符串上有多余的字符。但我需要它看起来像这样:
字符串1字符串2字符串3字符串
最佳答案
您可能希望在重写文件之前将其截断为零长度,如下所示:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
...
if (-1 == fseek(file, 0, SEEK_SET))
perror("fseek()");
if (-1 == ftruncate(fileno(file), 0))
perror("ftruncate()");
}
关于c - 在循环中将字符串写入文件会将多余的字符放在文件末尾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16611539/