Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets skip the blank line

Tags:

c

fgets

I am writing a C program that use fgets to read in each line from a file. The problem is that if the file have a blank line, how to skip it to get the next line ? This is what I had try so far but it did not work.

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;
            }
        }
like image 994
user4075830 Avatar asked Dec 05 '22 05:12

user4075830


2 Answers

Change

if (line != "\n")

into

if (line[0] != '\n')
like image 72
timrau Avatar answered Dec 22 '22 04:12

timrau


You can also use the strcmp function to check for newline

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

Also, answering to your comment, fgets increments the file pointer after reading the line from the file. If you are running the code on a Linux system, try doing man fgets for more details.

like image 31
Ashish_Deshpande Avatar answered Dec 22 '22 05:12

Ashish_Deshpande