目前尚不清楚您的文件中有多少int,并且当前存储它们的方式容易出错。 fgetc 返回一个 int 是 EOF (-1) 或 0-255,所以 ch 应该被声明为 int 然后当 (ch=getc(fp))!= EOF 为真时,ch 将包含 0- 255.
在下面的fscanf(fp, "%d", &a[ch]); 中,您再次从文件中读取,但读取到索引位置ch 的数组中,这显然不是您的意图(当您读取值> 9 的字符时,它也可能会崩溃。提示: '0' 的值为 48)。下面的解决方案可能看起来过于复杂,但我已经习惯了 C++,这些事情发生在幕后,你不必为此烦恼太多。也许你会通过去腌制得到一些想法。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
/* dynamic memory storage - start */
typedef struct {
size_t m_size;
size_t m_reserved;
int* m_data;
} store;
/* create a store */
store* store_create() {
store* s = malloc(sizeof(store));
if(s) {
/* initialize values */
s->m_size = 0;
s->m_reserved = 1; /* a very conservative start value */
s->m_data = malloc(sizeof(int)*s->m_reserved);
if(s->m_data==NULL) {
free(s);
s = NULL;
}
}
return s;
}
/* destroy a store */
void store_destroy(store* s) {
/* free the integer array */
free(s->m_data);
/* free the store struct */
free(s);
}
bool store_reserve(store* s, size_t new_res) {
/* reserve more space for the int's if needed */
if(new_res>s->m_reserved) {
int* n = realloc(s->m_data, sizeof(int)*new_res);
if(n==NULL) return false; /* could not expand storage */
s->m_reserved = new_res;
s->m_data = n;
}
return true;
}
// check if it's time to increase reserved storage
bool store_check_reserve(store* s) {
if(s->m_size == s->m_reserved)
/* change 5/4 to a larger value for more aggressive
* increase of memory allocation */
return store_reserve(s, (s->m_reserved+1)*5/4);
else
return true;
}
// add a value to the store
bool store_add(store* s, int v) {
if(!store_check_reserve(s)) return false;
s->m_data[s->m_size++] = v;
return true;
}
/* dynamic memory storage - end */
int main(int argc, char* argv[]) {
FILE* fp;
fp = fopen("file.txt", "r");
/* create a store for our unknown amount of int's */
store* myStore = store_create();
/* scan for strings separated by comma and newline
* and allocate memory for it */
char* str;
while(fscanf(fp, " %m[^,\n],", &str)==1)
{
int num;
/* convert string to integer */
if(sscanf(str, "%d", &num)==1) {
/* store the extracted value */
if(store_add(myStore, num)==false) {
fprintf(stderr, "FAILED STORING %d\n", num);
}
}
// free string allocated by fscanf (%m) */
free(str);
}
fclose(fp);
printf("All %d stored values:\n", myStore->m_size);
for(size_t i=0; i<myStore->m_size; ++i) {
printf("%d = %d\n", i, myStore->m_data[i]);
}
/* release memory allocated by our store */
store_destroy(myStore);
return 0;
}