Search code examples
cfileatoi

Reading a number from a file and converting it to an integer in C


I have a FILE variable, declared as FILE *fin. fin = fopen( "points.dat", "r" ); is initialized after the declaration. I've been trying to loop through fin while fgetc( fin ) != '\n'. Here's where I am stumped.

I want to store each character on line 1 of points.dat into a char *, which I can later invoke atoi on to store as an integer. How should I do this? I've tried it, but I keep getting segmentation faults and other weird errors. Here's my latest attempt:

FILE *fin;
char c;
int counter = 0;
int countPoints;
char *readFirst;

fin = fopen( "points.dat", "r" );

while( ( c = fgetc( fin ) ) != '\n' ) {

    readFirst[counter] = c;
    counter++;
}

countPoints = atoi( readFirst );

printf("%d\n", countPoints);

Note: this is not in its entirity a homework assignment. This is just a very small thing I need to get working before I can actually do the homework assignment.


Solution

  • You're getting a segmentation fault because char *readFirst; only declares a pointer, but it doesn't reserve any space to hold the data.

    Either declare readFirst directly as an array (char readFirst[size];) or use the function malloc() to allocate the space.