我正在编写一个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;
}
}发布于 2014-09-26 12:27:07
变化
if (line != "\n")转到
if (line[0] != '\n')发布于 2014-09-26 13:19:37
还可以使用strcmp函数检查换行符
//Check for dos and unix EOL format
if(strcmp(line,"\n") || strcmp(line,"\r\n"))
{
//do something
}
else
{
continue;
}此外,作为对您的注释的响应,fgets在从文件中读取行之后会递增文件指针。如果您在Linux系统上运行代码,请尝试执行man fgets以获取更多详细信息。
发布于 2019-03-04 05:43:28
if(strcmp(line,"\n") || strcmp(line,"\r\n")){...}错误。
如果不等于,则strcmp返回非零值。
line=="\n“
line=="\r\n“
line=="A“
对于此逻辑,将全部求值为true。
它在脑海中有的正确想法,,虽然很有帮助。
这是一个完整的工作程序重写:
//: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 );
};;https://stackoverflow.com/questions/26052014
复制相似问题