关于C语言中文本文件的逐行读取的实现

现有helloworld.txt文本文件。
void main()
{
while (1)
{
ReadData();
someprocess();
}
}
本程序的主要目的是,ReadData()函数每次从helloworld.txt中读取下一行内容,然后由someprocess()函数对读到的内容进行处理。
请大家不吝赐教!
这个ReadData()函数的实现难点是:
如果第i次调用ReadData()时读取的是第i行,那么第i+1次调用时读取的就是第i+1行。
第i次调用ReadData()时读取第i行后,ReadData()即执行结束。希望当第i+1次调用ReadData()函数时,它能读第i+1行。

第1个回答  2007-07-26
当读到换行符的时候就表示一行结束了
第2个回答  2018-07-25
#include<stdio.h>
#include<string.h>

#define BUFFER_SIZE 100
int main()
{
FILE *fp;
char *buffer;

/*打开目标文件*/
fp = fopen("my.cnf","r");
if(fp==NULL)
{
printf("打开文件失败!\n");
return -1;
}

char temp[BUFFER_SIZE]={0};//临时数组,用来保存前一次读取的行
while(fgets(buffer,BUFFER_SIZE,fp)!=NULL)
{
int ret = strcmp(buffer,temp);
if(ret == 0)
{
strcpy(temp,buffer);
continue;
}
printf("%s\n",buffer);
strcpy(temp,buffer);
}

fclose(fp);
return 0;
}

第3个回答  2007-07-27
hha
相似回答