我正在编写一个练习程序来读取文件中的整数并对它们进行排序。我对C中的文件IO有点困惑。到目前为止我的内容如下所示,我希望有人可以看看它并提供任何更正/建议,如果他们有任何...
// TODO: Open input file and do same as above
char *mode = "r";
FILE *fp = fopen(inputFile, mode);
if(fp == NULL){
fprintf(stderr, "Can't open input file!");
exit(1);
}
// Load the numbers into a buffer and get a count
int buffer[100];
int count = 0;
while(fscanf(fp, "%d", &buffer[count]) == 1) {
count++;
}
// Initialize the array with the proper size
integers = (int*)malloc(sizeof(count*sizeof(int)));
// Load the integers into the array
rewind(fp);
for(int i = 0; i < count; i++){
if(fscanf(fp, "%d", &integers[count] != 1)){
fprintf(stderr, "Error loading integers into array");
exit(1);
}
}
答案 0 :(得分:1)
fscanf()
返回成功读取的元素数,因此请检查要读取的所需元素数,在您的情况下,您只需读取数组值并增加索引即可。稍后使用index的值来分配内存。
int *temp;
integers = malloc(sizeof(int)));
while(fscanf(fp, "%d", &integers[index]) == 1)
{
index++;
temp = realloc(integers,sizeof(int) * (index+1));
if(temp != NULL)
integers = temp;
}