简体   繁体   English

在C中逐行读取文本文件

[英]Reading a text file line by line in c

I try to read the file that I wrote the first three line, line by line. 我尝试逐行读取我写的前三行文件。 However, it enters infinity loop. 但是,它进入无限循环。 How can I stop it at the end of the file? 如何在文件末尾停止它?

while(fscanf(infile, "%[^\n]", ch) != EOF)
   printf("%s", ch);


Tiffany;Evans Smith;F;22/01/1989;
Alex;Williams;M;23/06/1988;
Clay;Bristol;F;30/12/1989;

There are multiple ways of reading a text file line by line. 逐行读取文本文件有多种方法。 Hopefully, the following code answers your question. 希望以下代码可以回答您的问题。

  #include<stdio.h>
  #include<stdlib.h>

 int main()
 {
   FILE *infile;
   char data[BUFSIZ];

   infile=fopen("filename","r");

   while((fgets(data,BUFSIZ,infile)!=NULL))

  puts(data);
}

if you want to use fscanf, you can use this code : 如果要使用fscanf,可以使用以下代码:

int ret;        
while(ret = fscanf(infile,"%s",str))
{
    if (ret == EOF)
        break;
    if(ret >0 )
    {
        cout << str <<endl;
    }
    else
    {
        break;
    }
}

here, int ret is: 在这里,int ret是:

  • EOF, if the pointer is reached end of file. EOF,如果指针已到达文件末尾。
  • 0, if no input matched with the variable 0,如果没有输入与变量匹配
  • >0, number of matched variables with the file input > 0,与文件输入匹配的变量数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM