简体   繁体   中英

Read integers from file in C

1 2 3 4 5
1 2 3 4 5
1 2 3
2 5 7 8 9 8

I'm a beginner of C and I want to write a small program but I have this problem.

The problem is: if there is a file contains integers, the number of integers of each line is different but all within the maximum number of integers.

For example the integers above, the maximum number of integers for each line is 6, each line could have from 1 to 6 integers. The maximum number of integers will also change for each file.

How to store these numbers into a 2D array? Or store the integers into arrays line by line. (Don't worry about the empty values)

I have tried to use fscanf , but I don't know how to define the number of integers of each reading.

================================ Thanks everyone for the generous help, I've figured out using Joachim Pileborg's idea.

#define MAX_SIZE_BUFFER 1000

FILE *file;
int len = MAX_SIZE_BUFFER;
char sLine[MAX_SIZE_BUFFER];
int i, j, maxnumber = 6;
int *numbers, *temp;
char *sTok;

numbers = (int *) malloc(sizeof(int) * maxnumber);
for (i = 0; i < maxnumber; i++) {
    numbers[i] = -1;
}

while (fgets(sLine, len, file) != NULL) {
    i = 0;
    sTok = strtok(sLine, " ");
    while (sTok != NULL) {
        numbers[i] = atof(sTok);
        sTok = strtok(NULL, " ");
        i++;
    }

    /* This temp stores all the numbers of each row */
    temp = (int *) malloc(sizeof(int) * i);
    for (j = 0; j < i; j++) {
        temp[j] = numbers[j];
    }

}

The code above is not completed, but it's the idea how I do this.

One way to solve your problem is to start by reading line by line (using eg fgets ). Then for each line you need to separate the "tokens" (integers) which you can do with eg strtok in a loop. Finally, convert each "token" string to an integer using eg strtol .

let's try: fscanf(fp, "%d", value)

fp : file pointer.

"%d": format of the value that you want to read (it can be %c, %f, ...).

value: use it to keep the value you just read from the file.

Of course you should put it into the loop if you want to read all content in the file. EOF is the condition to break the loop.

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