c - How to check when fgets returns an empty line? -
this question has answer here:
- fgets skip blank line 2 answers
printf("batch mode\n"); file* batchfile; char oneline[line_max]; batchfile = fopen(argv[1], "r"); bool done = false; if(batchfile == null) { perror("file"); exit(1); } while (fgets(oneline,limit,batchfile) != null && !done) { processline(oneline, done); }
so have concern regarding code above. problem fgets still gets lines if lines contain newline character. need eliminate or @ least able check lines contain newline.
i tried
if (strcpy(line, '\n') == 0) { printf("an enter key line\n"); return; }
but still doesn't work.
how check when fgets returns empty line?
when line contains "\n", it's not considered empty.
the return of fgets()
contains returned result of function. if successful, function returns pointer nul-terminated string of characters. if function encounters end-of-file , reads no characters linebuffer, returns null pointer. if read error occurs, fgets returns null , sets errno nonzero value.
so, check possibilities.
change line:
while(fgets(oneline,limit,batchfile) != null && !done) //limit not size of //the buffer oneline
to
while (fgets(oneline,line_max,batchfile) != null && !done) { if (errno != 0 ) {//handle error, exit} //proceed normal line processing if (strcmp(oneline, "\n") != 0)//strcmp verifies line has more \n { processline(oneline,done); }
Comments
Post a Comment