-1
我正在尝试读取文件并获取文件内容并将其存储在2个元素数组[0]中:用于内容[1]:用于NULL值。此代码工作正常时,正是我要打印出来,但我想作为一个数组来使用:读取文件并存储到数组
char ch;
FILE *file;
file = fopen("input.txt","r");
int allocated_size = 10;
int used_size = 0;
char c, *input, *tmp_input;
// allocate our buffer
input = (char*)malloc(allocated_size);
if (input == NULL) {
printf("Memory allocation error");
return 1;
}
while ((c = fgetc(file)) != EOF){
// make sure there's an empty one at the end to avoid
// having to do this check after the loop
if (used_size == allocated_size-1) {
allocated_size *= 2;
tmp_input = (char*)realloc(input, allocated_size);
if (tmp_input == NULL) {
free (input);
printf("Memory allocation error");
return 1;
}
input = tmp_input;
}
input[used_size++] = c;
}
// we are sure that there's a spot for last one
// because of if (used_size == allocated_size-1)
input[used_size] = '\0';
printf("\nEntered string in the file: %s\n", input);
但我怎么可以用“输入”像数组:
char *input[] = {"This is string value from file!", NULL};
对于这种情况,我可以接触到的文字是这样的:input[0]
'因为if(used_size == allocated_size-1)'错误。 used_size varable已经在你退出循环时增加了。 (添加一个assert(),你会看到它一次) – wildplasser 2014-09-13 15:46:08