fgets跳过空白行

时间:2014-09-26 04:24:41

标签: c fgets

我正在编写一个C程序,它使用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;
            }
        }

3 个答案:

答案 0 :(得分:7)

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

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

另外,回答你的评论后,fgets会在读取文件中的行后递增文件指针。如果您在Linux系统上运行代码,请尝试执行man fgets以获取更多详细信息。

答案 1 :(得分:6)

更改

if (line != "\n")

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

答案 2 :(得分:0)

if(strcmp(line,“ \ n”)|| strcmp(line,“ \ r \ n”)){...}错误。

strcmp返回不为零的值。

line ==“ \ n”

line ==“ \ r \ n”

line ==“ A”

对于此逻辑,所有结果都将为真。

它具有正确的想法,并且很有帮助。

这是一个完整的工作程序,需要重写:

//: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 );

};;