【问题标题】:C programming: how to fopen a designated file and dynamically allocate its contents into a 2D array?C 编程:如何打开指定文件并将其内容动态分配到二维数组中?
【发布时间】:2013-02-03 09:47:26
【问题描述】:

基本上,我的程序会提示用户输入他想要打开的文件的名称。我的程序应该打开该文件并将其内容扫描到二维数组中。但是你怎么做才能让程序打开用户指定的文件呢?到目前为止,这是我的代码:

#include <stdio.h>
#include <string.h>
FILE *open_file(int ar[3][4]);

int main()
{
  FILE *fp;
  int ar[3][4];

  fp = open_file(ar);
}

FILE *open_file(int ar[3][4])
{
  FILE *fp;
  int i;
  char file[80];
  printf("Please input file name ");
  scanf("%s", &file); //am I supposed to have written ("%s", file) instead?
  fp = fopen("%s", "r");// very confused about this line; will this open the file?
  for (i = 0; i < 12; i++)
    fscanf(fp, "%d", &ar[i][]); //how do you scan the file into a 2D array?
}

要使用 malloc,我必须编写类似 fp = (int *)malloc(sizeof(int));?

【问题讨论】:

    标签: c arrays multidimensional-array fopen scanf


    【解决方案1】:

    变量file 包含用户输入的文件名,所以将它传递给fopen。你有一个格式字符串。

    fp = fopen(file, "r");
    

    【讨论】:

      【解决方案2】:
      scanf("%s", &file); // am I supposed to have written ("%s", file) instead?
      

      是的,但不是你想的那样。所以

      scanf("%s", file);
      

      是正确的(解释:%s 格式说明符告诉 scanf() 期待 char *,但如果您编写 addressof 运算符,则传递给它的是 char (*)[80],并且 @987654327 的类型说明符不匹配@ 和 scanf() 调用未定义的行为)。

      fp = fopen("%s", "r"); // very confused about this line; will this open the file?
      

      不,不会。它将打开名为%s 的文件。你必须写

      fp = fopen(file, "r");
      

      相反。不要假设你可以使用你不能使用的格式字符串。

      【讨论】:

      • 哦,我明白了。谢谢你。您能帮我使用 malloc 将文件内容动态分配到数组中吗?
      • +1:非常有趣。你能再解释一下吗? malloc 和使用...请在答案正文中
      • @qPCR4vir 具体来说? (抱歉,我不会在 SO cmets 中进行完整的讲座。您应该搜索完整且详尽的 C 教程并学习该语言。)
      • 好的。但这并不是 malloc 的简单使用。
      • @qPCR4vir 你这是什么意思?什么不是微不足道的? (或者类似地,malloc() 的一个微不足道的用途是什么,即使是 3 岁的孩子甚至不知道 C 也能做到?)
      猜你喜欢
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 2021-02-03
      相关资源
      最近更新 更多