0

I have a basic C program that I have to do for a Personal Software Processes assignment. I'm fairly new to C so I honestly can't see where I've gone wrong. Please read through and let me know what I'm doing that's causing it to crash?

I've got to read in a file, and store the values as an array. It comes up with no compiling errors, just a segmentation fault.

#include <stdio.h>
#define array_limit   100

int main (void)

{  
  FILE *ifp;
  char *mode = "r";
  ifp = fopen("samplepopulation.txt", mode);  


  if (ifp==NULL)
  {
    printf("cannot read file \n");
  }  
  else
  {   
    int i;
    float sample; 

    float values[array_limit];
    i = 0;

    do
    {
       fscanf(ifp, "%f", &sample);
       if (!feof(ifp))
       {
          values[i] = sample;
          printf("%f \n", values[i]);
          i++;
            if (i>array_limit)
            {
               printf("File larger than allowed/n");
               break;
            }
       }

       else
       {
          printf("read complete");
       }

    } while (ifp!= EOF);     
  }

  fclose(ifp);

  return 0;
}
alk
  • 69,737
  • 10
  • 105
  • 255
jesspick
  • 1
  • 1

2 Answers2

0

Change

while (ifp!= EOF);  

to

while (!feof(ifp)); 

Also scan from file like this:

if (fscanf(ifp, "%f", &sample)==EOF) //EOF if input failure
   break;
HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
  • And in addition, check the result from fscanf and see if it is EOF. The code seems to have confused when to use feof() and when to check for EOF. – Lundin Mar 31 '14 at 13:54
  • What if read fails with ferror? In that case feof will never be true and hence it'll be infinite loop. – avmohan Mar 31 '14 at 13:54
  • "The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure." – Lundin Mar 31 '14 at 13:56
  • `while(!feof(ifp))` is just plain wrong, [this has been explained over, and over, and over](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – Elias Van Ootegem Mar 31 '14 at 14:31
  • @EliasVanOotegem But here the read error is being taken care of. So this works fine. – HelloWorld123456789 Mar 31 '14 at 14:33
  • 1
    @RikayanBandyopadhyay: `EOF` isn't an error, `ferror` isn't dealt with at all. If there really was a read-error, then checking for `feof` will get you nowhere. Besides, I think the issue here could well be `fclose(possible_null_ptr);` – Elias Van Ootegem Mar 31 '14 at 14:37
0

You might like to change this

fclose(ifp);

to become

if (NULL != ifp)
{
  fclose(ifp);
}

or simply move into the else branch:

    ...

    fclose(ifp)
  }

  return 0;
}
alk
  • 69,737
  • 10
  • 105
  • 255