我有一个文件,我想逐行读取,但它必须动态完成,这意味着它应该只在我调用该方法时读取一行。一旦我下次调用该方法,它应该读取文件的下一行,依此类推。 到目前为止,我只成功地读取了文件中的所有行,或者一遍又一遍地读取了同一行。
这是我的代码片段:
文件方法:
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/