从文件扫描,最后一个字符串重复

时间:2013-10-07 22:55:40

标签: c file scanf

我的代码遇到了一些麻烦。我正在尝试读取保存到文件中的一些以前的命令,并将它们放在我的数组中以供以后使用。

以下是我的相关代码:

    if( (pastHist = fopen("history.txt", "r+")) == NULL)
  {
pastHist = fopen("history.txt", "w+");
  }  
else
  {

printf("%s", "INSIDE the else!");
pastHist = fopen("history.txt", "r+");
fscanf(pastHist, "%s", fstring);
while (fstring != NULL)
  {
    printf("%s %s", "the read in string is: ", fstring);
    strcpy(cmndLine[cmndIndex], fstring);
    strcpy(cmndLinecpy[cmndIndex], fstring);
    cmndIndex++;
    cmndNum++;
    fscanf(pastHist, "%s", fstring);
  }
  }

现在代码写入文件很好。 (写作部分在其他地方举行)。如果我从我之前写过的文件中读取并且文件说:

LS rmdir天使 历史

然后我用这个print语句仔细检查我正在阅读的内容......它打印出来 “INSIDE the else!读取字符串是:lsthe read in string is:rmdirthe read in string is:angelthe read in string is:historythe read in string is:historythe read in string is:history

......并且它重复了最后读取的内容是历史上的一百万次。为什么会这样?我也尝试了while条件

while(getchar() != EOF)

但这给了我同样的东西。

请帮忙。 感谢。

1 个答案:

答案 0 :(得分:1)

通过调用fstring,永远不能将

fscanf设置为NULL。您要检查的是fscanf返回值

你的getchar()循环同样没有用 - 它是从标准输入读取的,而不是从你的文件中读取。

相关问题