我正在尝试读取文件并获取文件内容并将其存储在 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 和重新分配等使用 input[0] 。这样数组的第一条记录将包含您的文本。
这背后的原因是,第一条记录中的字符串意味着您需要 char 指针数组。
关于c - 读取文件并存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25824787/