【问题标题】:writing strings to file in a loop puts extra chars at the end of file在循环中将字符串写入文件会在文件末尾放置额外的字符
【发布时间】:2013-05-17 14:28:14
【问题描述】:

我正在将一些字符串写入文件,然后将其倒回。这个,我在循环中做。
实际上,它工作得很好,但是在文件的末尾,它从最后一个字符串中复制了一些字符。我如何摆脱多余的字符?

所以,我有一个循环,它将字符串写入文件,并在每次循环结束时回退:

for 循环{
fputs("string1\n",file);
fputs("string2\n",file);
fputs("string3\n",file);
fputs("stringLAST",file) ;
fseek(file,0,SEEK_SET);} // 或使用 rewind(file);我得到了同样的结果。

因此我的文件看起来像这样:

string1
string2
string3
stringLASTstringLASTASTASTSTST

现在,stringLAST 字符串上有多余的字符。但我需要它看起来像这样:

string1
string2
string3
stringLAST

【问题讨论】:

  • 它们可能是上一次运行遗留下来的。我看到你正在寻找和倒带。如果您在列出的代码之前打开文件进行输出(删除或截断),它可能会正常工作。
  • 您在检查错误吗? fputs 出错时返回 EOF。您是否尝试过刷新文件?倒带时,它可能仍然在缓冲区中。
  • 是的,我必须用ftruncate(fileno(file),0) 截断它。现在,我必须查一下这意味着什么。
  • 肮脏的解决方案是,在文件末尾放置一个用空格填充的额外字符串。

标签: c gcc


【解决方案1】:

您可能希望在重写之前将文件截断为零长度,如下所示:

#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()");
}

【讨论】:

  • 谢谢,效果很好,但没有第一个 if 语句。包含第一个 if 语句后,整个文件变为空白。
猜你喜欢
  • 2011-10-19
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2012-12-26
  • 2013-03-20
  • 1970-01-01
相关资源
最近更新 更多