简体   繁体   中英

C read a number of lines with fgets

I am trying to read a file into a 2d array.

The first line contains the sizes of the array (eg 4, 3) I then need to create a 4x3 and a 3x4 array and read in the values.

I am getting segmentation fault. Is it because I need to rewind after using sscanf ?

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

#define LINE_LEN 100
int main(int argc, char ** argv)
{
    int ** arr1;
    int ** arr2;
    int i,col,row;
    FILE * dfile;
    char line[LINE_LEN];
    char * token;
    int num1,num2;
    const char delim[2] = " ";

    if ((dfile = fopen(argv[1], "r")) == NULL) {
        fprintf(stderr, "Error opening input file.\n");
        exit(EXIT_FAILURE);
    }

    fscanf(dfile, "%d %d\n", &num1, &num2);

    arr1 = malloc(num1 * sizeof(int*));
    for (i = 0; i < num1; i++) {
        arr1[i] = malloc(num2* sizeof(int));
    }


    arr2 = malloc(num2 * sizeof(int*));
    for (i = 0; i < num2; i++)
    {
        arr2[i] = malloc(num1 * sizeof(int));
    }

    col = 0;        
    for(i=0; i<num1; i++)
    {
        row = 0;
        fgets(line, LINE_LEN, dfile);
        token = strtok(line, delim);
        while (token != NULL)
        {
            token = strtok(NULL, delim);
            arr1[col][row] = atoi(token);
            row++;
        }
        col++;
    }

    col=0;
    for(i=0; i<num2; i++)
    {
        row=0;
        fgets(line,LINE_LEN,dfile);
        token = strtok(line,delim);
        while(token != NULL)
        {
            token = strtok(NULL,delim);
            arr2[col][row] = atoi(token);
            row++;
        }
        col++;
    }
}

example of file

4 3
0 0 1 2
1 1 0 2
2 1 2 0
3 1 0 2
0 0 1 2 3
2 2 3 1 0
1 2 1 3 0
  • NULL is passed to atoi function and it causes Segmentation Falut. Check if token isn't NULL before passing it to atoi .
  • The example of file is bad because there are one extra number on each lines after the line of num1 and num2 and it leads to out-of-bounds access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM