YlmzCmlttn_Old
YlmzCmlttn_Old

Reputation: 89

How to detect last extra Empty Line and Ignore it in C (using getc)

Hello I am using this code for reading floating numbers in txt. If end of txt file has extra blank empty line program reads it 0.00000 and this affect my calculation Last empty line

(# means end of the calculation I added comment line if it exist update comment line)

I try "getline" and other function I can't fix it

fptr = fopen(fileName,"r+"); 
    if(fptr == NULL){
        printf("Error!! Cannot open file: %s \n", fileName );
        return 1;
    }
    else {
        printf("File opened successfully\n");
        while((c = getc(fptr)) != '#' && c != EOF) {    

            fscanf(fptr,"%f" ,&arr[i]);      
            ++i;
        }
    }

Upvotes: 0

Views: 359

Answers (2)

chux
chux

Reputation: 154592

OP is reading a file, line by line and has 4 outcomes:

  1. Successful translated to a number.
  2. Line begins with a # or whitespace only.
  3. No more input (end-of-file).
  4. Something else.

Suggest new approach: read line by line as text and then attempt various parsings. It is important to check the return value of *scanf() to help determine success.

   printf("File opened successfully\n");
   float /* or double */ arr[N];
   size_t i = 0;
   char buffer[100];

   while (fgets(buffer, sizeof buffer, fptr)) {
     double x;
     char sof[2];
     if (sscanf(buffer, "%lf" ,&x) == 1) {
       if (i < N) {
         arr[i++] = x;
       } else {
         puts("No room");
       }
     } else if (sscanf(buffer, "%1s" , sof) != 1 || sof[0] == '#') {
       ; // quietly ignore white-space only lines and that begin with # 
     } else {
       puts("Unexpected input");
     }
   }
   fclose(fptr);
   puts("Done");

Upvotes: 1

Lou Franco
Lou Franco

Reputation: 89242

Check the return value of fscanf -- it should return 1 when it successfully reads a number and 0 on that blank line.

Upvotes: 4

Related Questions