我的代码从C语言文件中读取数据时遇到问题:
typedef struct Data {
int _num_of_lines;
int **_the_data;
int *_linse_len;
} Data;
void readFile(char *f, Data *d) {
FILE *in;
char str[1000];
in = fopen(f, "r");
int i = 0;
char *try;
while (!feof(in)) {
fgets(str, 100, (FILE*)in);
if (i == d->_num_of_lines) {
if (d->_num_of_lines == 0) {
i++;
d->_the_data = (int**)malloc(sizeof(int*));
d->_linse_len = (int*)malloc(sizeof(int));
} else {
i *= 2;
d->_the_data = (int**)realloc(d->_the_data, i * sizeof(int*));
d->_linse_len = (int*)realloc(d->_linse_len, i * sizeof(int));
}
}
try = strtok(str, " ");
printf("%s\n", try);
d->_linse_len[d->_num_of_lines] = atoi(try);
d->_the_data[d->_num_of_lines] = (int*)malloc(d->_linse_len[d->_num_of_lines] * sizeof(int));
int j;
for (j = 0; j < d->_linse_len[d->_num_of_lines]; j++) {
try = strtok(NULL, " ");
printf("-->%s\n", try);
d->_the_data[d->_num_of_lines][j] = atoi(try);
}
d->_num_of_lines++;
}
d->_the_data = (int**)realloc(d->_the_data, d->_num_of_lines * sizeof(int*));
d->_linse_len = (int*)realloc(d->_linse_len, d->_num_of_lines * sizeof(int));
fclose(in);
}
这是我编写的函数,正在读取包含以下内容的文件
5 1 2 3 4 5
3 0 0 0
1 -17
在输出中我得到这个:
5
-->1
-->2
-->3
-->4
-->5
3
-->0
-->0
-->0
1
-->-17
1
-->(null)
我不知道它从哪里读取最后两个值。
我正在CentOS Linux上运行它;在我在Windows上运行此代码之前,它很好,并且没有获取最后两个值。