试图从文件中读取一系列整数
Trying to read a series of integers from a file
我正在编写一个练习程序来从文件中读取整数并对它们进行排序。我对 C 中的文件 IO 有点困惑。我目前所拥有的在下面,我希望有人可以看一下它并提供任何 corrections/suggestions 如果他们有...
// 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);
}
}
fscanf()
returns 成功读取的元素数量因此请检查需要读取的元素数量,在您的情况下,您只需将值读取到数组并增加索引。稍后使用索引的值分配内存。
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;
}
我正在编写一个练习程序来从文件中读取整数并对它们进行排序。我对 C 中的文件 IO 有点困惑。我目前所拥有的在下面,我希望有人可以看一下它并提供任何 corrections/suggestions 如果他们有...
// 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);
}
}
fscanf()
returns 成功读取的元素数量因此请检查需要读取的元素数量,在您的情况下,您只需将值读取到数组并增加索引。稍后使用索引的值分配内存。
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;
}