2014-09-26 140 views
2

我正在写一个C程序,它使用fgets从文件中读取每一行。问题是,如果文件有一个空行,如何跳过它来获得下一行?这是我到目前为止的尝试,但没有奏效。fgets跳过空行

char line[100]; 
FILE *filePtr = fopen(filename, "r"); 
    while(fgets(line, sizeof(line), filePtr) != NULL)  //read each line of the file 
     { 
      if (line != "\n") 
      { 
       //do something 
      } 
      else 
      { 
       continue; 
      } 
     } 

回答

6

变化

if (line != "\n") 

if (line[0] != '\n') 
+0

谢谢,它现在工作。但我不明白,增加行数组是因为我应该像'for(i = 0; i user4075830 2014-09-26 04:32:11

6

您还可以使用strcmp函数检查换行符

//Check for dos and unix EOL format 
if(strcmp(line,"\n") || strcmp(line,"\r\n")) 
{ 
    //do something 
} 
else 
{ 
    continue; 
} 

此外,在回答您的意见,FGETS增量读取th后的文件指针e从文件中删除。如果您在Linux系统上运行代码,请尝试执行man fgets以了解更多详细信息。

+0

很好的方法可以在多个系统上运行。 – LeoPucciBr 2016-12-15 15:30:32