Read in Numbers from a File in C

后端 未结 2 1594
醉话见心
醉话见心 2021-01-07 07:34

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 pai

相关标签:
2条回答
  • 2021-01-07 08:19
    #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.

    0 讨论(0)
  • 2021-01-07 08:26

    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.

    0 讨论(0)
提交回复
热议问题