从 C 文件中读取整数

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

我是C初学者,想写个小程序,遇到这个问题

问题是:如果有一个文件包含整数,每行的整数个数不同,但都在最大整数个数之内。

例如上面的整数,每行最多有6个整数,每行可以有1到6个整数。每个文件的最大整数数量也会发生变化。

如何将这些数字存储到二维数组中?或者将整数逐行存储到数组中。 (不用担心空值)

我试过用fscanf,但不知道如何定义每次读数的整数个数

================================ 感谢大家的慷慨帮助,我想出了用 Joachim Pileborg 的想法。

#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];
    }

}

上面的代码还没有完成,但这是我的想法。

一个 解决问题的方法是开始逐行阅读(使用例如 fgets). Then for each line you need to separate the "tokens" (integers) which you can do with e.g. strtok in a loop. Finally, convert each "token" string to an integer using e.g. strtol.

让我们试试:fscanf(fp, "%d", value)

fp : 文件指针。

"%d": 您要读取的值的格式(可以是 %c, %f, ...)。

value:用它来保存你刚刚从文件中读取的值。

当然要读取文件中的所有内容就应该放入循环中。 EOF 是打破循环的条件。