c - 读取文件并存储到数组中

标签 c file file-io

我正在尝试读取文件并获取文件内容并将其存储在 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/

相关文章:

c - 写入相同值的竞争条件是否安全?

file - 套接字描述符基本上是文件描述符的同义词吗?

file - 在 HTML 页面中包含文件中的 JSON-LD 或微数据?

linux - 将数据流式传输到 Linux 设备驱动程序中的文件中

c - ftello/fseeko 与 fgetpos/fsetpos

c++ - 分部分读取文件,在最后读取的部分之后继续

更改 PointerArray 的值

c++ - 如何在 C++ 中的 2 个函数集之间切换?

c - 查找谁使用了 ELF 文件中的符号

Java:登录系统无法工作