Search code examples
cdebuggingfile-ioblank-line

C File Reading , Blank/Empty Line


Helo,

  if('\t' == input [0] ||'\v' == input [0] ||'\r' == input [0] ||'\n' == input [0] || '\0' == input[0] || '' == input[0])

input is the array of chars :)

This is the line of code ive got checking for a blank line in a file, but it never picks up a blank line for example..

My code reads in 8 digit hex values and i want to termiated when its invalid(already sorted) or when theres a empty line,line with white space or EOF.

It works if my file is like this... 11111111 11111111

^with a space on the empty line but if theres no space it just breaks in to a infitie loop this is very annoying.

#define MAXIN 4096 
  static char input[MAXIN]; 
  char last;
    /*Reading the current line */
  fgets(input, MAXIN, f);;
  if (input[8] == '\r') input[8] = '\0';
  /* First of all check if it was a blank line, i.e. just a '\n' input...*/
  if('\t' == input [0] ||'\v' == input [0] ||'\r' == input [0] ||'\n' == input [0] || '\0' == input[0] || '' == input[0])
  {printf("##EMPTY");return(INERR);}
  if ('\n' == input[0]) return(INERR); 

 if ((sscanf(input,"%8x%c",&result,&last) < 2)) return(INERR);
  if ('\n' != last) return(INERR);  
}

Solution

  • You need to check the return value of fgets. This function returns NULL to signal "end of file". Simply put, try this:

    if (!fgets(input, MAXIN, f))
        return INERR;