Mxyk
Mxyk

Reputation: 10698

Read in Numbers from a File in C

I have a file called points.dat which reads something like:
5
2 5
-1 18
0 6
1 -1
10 0

The first number is how many ordered pairs there are. The next 5 lines contain those ordered pairs. What can I do to read in the first number, determine how many points there are (from here I can malloc an array of structs to store the points in).

My problem is that fgetc doesn't really do the job here. What if the first number is two digits? Say the first number is 10. fgetc will only retrieve the '1'. Also, fgets doesn't really work, since you need to supply it the length of the amount of characters you want to read in. The same applies for fscanf.

The real trouble comes in when it's time to retrieve the ordered pairs. I have no idea how to do this either. My only thoughts so far is look at a line: if it sees non-spaces or non-'\n's, it will read in the number as the x coordinate of point 1. Loop. Get y coordinate. Once it hits a '\n', it will now move on to the next line, and begin looking for values to store in the next struct in the array of structs.

(While doing this, I also need to be sure atoi can convert all of these into integers... ).

If anyone has any ideas to help, they are appreciated.

Upvotes: 1

Views: 13026

Answers (2)

John
John

Reputation: 6708

#include <stdio.h>
#include <stdlib.h>

typedef struct {
        int x, y;
} Point;

int main ()
{
        int numOf;
        Point *myPoints = NULL;
        FILE *myfile = fopen ("myfile.txt","r");
        if (myfile == NULL)
            perror ("Error opening file"); //or return 1;
        else
        {
            fscanf(myfile, "%d", &numOf);
            myPoints = (Point *)malloc(sizeof(Point) * numOf);
            while ( !feof (myfile) && numOf-- )
            {
                fscanf(myfile, "%d %d", &(myPoints[numOf].x), &(myPoints[numOf].y));
            }
        }
        fclose(myfile);
        //Do stuff with array
        free ((void *)myPoints);
        getchar();//Press enter to close debugger etc.
        return 0;
}

Sorry for the delay.

Upvotes: 4

xanatos
xanatos

Reputation: 111950

For the first line use int numValuesRead = fscanf(file, "%d", &totnums);

Then, use numValuesRead = fscanf(file, "%d %d", &num1, &num2); to read the other lines.

fscanf returns the number of value read. You should always check it.

Upvotes: 5

Related Questions