【问题标题】:reading every line in a text file issue in C在 C 中读取文本文件中的每一行问题
【发布时间】:2015-01-10 21:13:26
【问题描述】:

代码:

#define maxWords 200
//finput is the file
char tempWord[maxWords];
(for i = 0; i < lineCounter(f); i++)
{
     fgets(tempWord, maxWords, finput);
     printf("%s", tempWord);
}

lineCounter 函数工作正常,并在文本文件中输出正确数量的行。但由于某种原因,它只打印了我不明白的 1500 行中的 150 行。我一直在尝试其他功能,例如 fscanf 和其他功能,但我仍然遇到同样的问题。它们都打印出文本,但不是整个文本文件。

即使我将i &lt; 1500 作为 for 循环中的条件,我仍然有这个问题。有谁知道为什么?我也尝试过 while-loop 形式,但没有运气。

我也知道有很多与阅读文本文件相关的主题,我已经阅读了它们,但我仍然有这个问题..

【问题讨论】:

  • 添加更多代码。 tempWord,maxWords 是如何定义的?
  • lineCounter 函数实际上在做什么?要从头到尾读取文件,您应该检查fgetsfeof(finput) 的返回值。另请注意,使用 getline 而不是 fgets 可以极大地帮助简化和增强您的代码。
  • maxWords 太小是候选问题。
  • 很高兴看到maxWords,但是一行中char 的最大数量是多少?如果是 199 或更多,代码需要更大的缓冲区。
  • 建议while (fgets(tempWord, maxWords, finput) != NULL) printf("%s", tempWord);

标签: c output text-files


【解决方案1】:

这个小程序应该打印出整个文本文件的行号和行本身。

#define INPUT_FILE 1
#define LINE_LEN 200

int main(int argc, char *argv[]) {
    int line_num;
    char string[LINE_LEN];
    FILE *file;
    if((file = fopen(argv[INPUT_FILE], "r")) == NULL) {
        fprintf(stderr, "Could not open input file\n");
        exit(1);
    }
    line_num = 1;
    while( fgets(string, LINE_LEN, file) != NULL ) {
        line_num++
        printf( "Line %d: <%s>\n", line_num, string);
    }
    return 0;
}

编辑: 将line_num初始化为1并按照@chux的建议添加标签

【讨论】:

  • 如需更多调试信息,建议"Line %d: &lt;%s&gt;\n",可打印的内容。
猜你喜欢
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
相关资源
最近更新 更多