C编程: how to fopen a designated file and dynamically allocate its contents into a 2D array?

标签 c arrays multidimensional-array fopen scanf

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

#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)); 的内容?

最佳答案

scanf("%s", &file); // am I supposed to have written ("%s", file) instead?

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

scanf("%s", file);

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

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

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

fp = fopen(file, "r");

相反。不要假设您可以使用无法使用的格式字符串。

关于C编程: how to fopen a designated file and dynamically allocate its contents into a 2D array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14945184/

相关文章:

c++ - 具有动态行数和固定列数的二维数组的初始化。 C++

c - 将链表拆分为半个 C 编程

c++ - sip调用中主叫和被叫如何共享RTP的ssrc值?

找不到段错误。在任何一种情况下都发生在第一次打印之前

arrays - Swift 字符串数组的索引号

java - java中的一维数组到二维数组

java - 我可以在不编译的情况下获得 C/C++/Java 代码的 XML AST 吗?

C++ 类模板构造函数——用数组 (U*) 重载引用 (U&) 失败

c++ - Arduino 数组中的损坏值

c++ - 使用二维数组作为参数的函数调用