读取文件并存储到数组
问题描述:
我正在尝试读取文件并获取文件内容并将其存储在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]
答
因此,为了实现这一目标
char *input[] = {"This is string value from file!", NULL};
如果我正确地从你写了理解然后声明输入,因为这
char *input[2];
每一次你在你的字符串的指针进行任何操作,例如时间malloc和重新分配等使用输入[0]。这样数组的第一条记录将包含您的文本。
背后的原因,第一个记录中的字符串意味着你需要数组的char指针。
'因为if(used_size == allocated_size-1)'错误。 used_size varable已经在你退出循环时增加了。 (添加一个assert(),你会看到它一次) – wildplasser 2014-09-13 15:46:08