c - C中使用方法从文件 "dynamically"逐行读取文件

标签 c readfile

我有一个文件,我想逐行读取,但它必须动态完成,这意味着它应该只在我调用该方法时读取一行。一旦我下次调用该方法,它应该读取文件的下一行,依此类推。 到目前为止,我只成功地读取了文件中的所有行,或者一遍又一遍地读取了同一行。

这是我的代码片段:

文件方法:

int getNextData(){
static const char filename[] = "file.txt";
   FILE *file = fopen ( filename, "r" );
   if ( file != NULL )
   {
      char line [ 5 ]; /* or other suitable maximum line size */

      if ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {
         fputs ( line, stdout ); /* write the line */
      }
   }
   else
   {
      perror ( filename ); /* why didn't the file open? */
   }
   return 0;
}

主文件:

int main () {
     // this should give me two different numbers
getNextData();
    getNextData();
return 0;
}

我省略了“include”,但那部分是对的。

在这种情况下输出是同一行两次。

谁能帮帮我?

最佳答案

问题很可能是您每次都打开文件,从而重置了文件指针。尝试在主函数中只打开一次并将文件句柄传递给函数以进行读取。

这里有一些应该适合你的修改后的代码:

#include <stdio.h>

int getNextData(FILE * file){

   if ( file != NULL )
   {
       char line [ 5 ]; /* or other suitable maximum line size */

       if ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */       
       {          
          fputs ( line, stdout ); /* write the line */       
       }    
   }    

  return 0; 
}

int main () {      // this should give me two different numbers 
  static const char filename[] = "file.txt";
  FILE *file = fopen ( filename, "r" );
  getNextData(file);     
  getNextData(file); 
  return 0; 
} 

使用此代码,给定文件:

mike@linux-4puc:~> ls -l file.txt
-rw-r--r-- 1 mike users 15 Sep 11 18:18 file.txt
mike@linux-4puc:~> cat file.txt
bye
sh
ccef

我看到了:

mike@linux-4puc:~> ./a.out 
bye
sh

关于c - C中使用方法从文件 "dynamically"逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12388212/

相关文章:

javascript - 通过 NodeJS 使用 HTML 文件加载 JS 文件的正确方法

node.js - 如何将使用 fs.readFileSync() 的 Node.js 代码重构为使用 fs.readFile()?

c - 多个定义在 gcc 或 clang 中都不会给出错误或警告

c - 为什么在打印特定范围的素数后会得到内存位置值?

c - 如何关闭 C 语言中的指数表示法?

C-线程和进程-防止僵尸

在C中将二进制字符串转换为int

C# IF 语句不排除字符串

c - 为什么从文件中读取()总是以分界线结尾

java - 将文本文件中的数字输入到 ArrayList 中,同时计算每个数字的出现次数