fgets skip the blank line

和自甴很熟 提交于 2019-11-29 08:05:54

Change

if (line != "\n")

into

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

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.

if(strcmp(line,"\n") || strcmp(line,"\r\n")){...} is wrong.

strcmp returns non-zero if not equal to.

line=="\n"

line=="\r\n"

line=="A"

Would all evaluate to true for this logic.

It has the right idea in mind and was helpful though.

Here is a full working program re-write:

//:for: uint32_t
#include <stdint.h> 

//:for: fopen, fgets, feof, fflush
#include <stdio.h>  

int main(){
    printf("[BEG:main]\n");fflush(stdout);

    size_t num_non_empty_lines_found = 0;
    FILE* file_pointer = NULL;
    const char* file_name = "RFYT.TXT";
    file_pointer = fopen( file_name, "r" );

    //: Init to null character because fgets
    //: will not change string if file is empty.
    //: Leading to reporting that an empty file
    //: contains exactly 1 non-blank line.
    //:
    //: Macro contains todays date, as a paranoid
    //: measure to ensure no collisions with
    //: other people's code.
    #define JOHN_MARKS_MAX_LINE_2019_03_03 256
    char single_line[ 
        JOHN_MARKS_MAX_LINE_2019_03_03 
    ] = "\0";
    int max_line = JOHN_MARKS_MAX_LINE_2019_03_03;
    #undef  JOHN_MARKS_MAX_LINE_2019_03_03

    //: This could happen if you accidentially
    //: spelled the filename wrong:
    if(NULL==file_pointer){
        printf("[ERROR:CheckFileNameSpelling]\n");
        return( 1 );
    };;

    //# DONT DO THIS! If you spelled the file  #//
    //# name wrong, this condition will lead   #//
    //# to an infinite loop.                   #//
    //- while( !feof(file_pointer )){ ... }    -//  
    while(fgets( 
    /**/single_line 
    ,   max_line
    ,   file_pointer 
    )){

        //: Check for empty lines:
        if( strcmp(single_line,"\n"  ) != 0 &&
            strcmp(single_line,"\r\n") != 0 &&
            strcmp(single_line,"\0"  ) != 0 &&
        1){
            printf("[LINE_HAS_CONTENT]\n");
            num_non_empty_lines_found++;
        }else{
            printf("[LINE_IS_EMPTY]\n");
            continue;
        };;

        //: Do stuff with non empty line:
        printf( "[Content]:%s\n", single_line );
    };;

    if(num_non_empty_lines_found<1){
        printf("[WARNING:FileWasEmpty]\n");
        printf("[EmptyFileName]:%s\n", file_name);
        fflush(stdout);
    };;

    printf("[END:main]\n");fflush(stdout);
    return( 0 );

};;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!