【发布时间】:2015-02-05 03:12:52
【问题描述】:
我正在编写一个练习程序来从文件中读取整数并对其进行排序。我对 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);
}
}
【问题讨论】:
-
你在哪里清除整数数组?
-
@PeerNet 它是一个全局 int 指针。我只包含了我的程序的一个功能
-
@JayB 你知道
n在fscanf()中做了什么吧?读取的字符数,如果文件中有 10 个字符,你的输入是什么? -
@Gopi 仅供参考,请参阅this answer。这就是代码的来源,但 OP 误用了答案。
-
@user3386109 我完全按照你写的那样做,但我正在尝试重新应用它来读取文件......