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