[英]C programming: how to fopen a designated file and dynamically allocate its contents into a 2D array?
基本上,我的程序会提示用户输入要打开的文件的名称。 我的程序应该打开该文件并将其内容扫描到2D数组中。 但是,您如何做才能使程序打开用户指定的文件? 到目前为止,这是我的代码:
#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()
类型说明符不匹配,则将其传递给char (*)[80]
和scanf()
调用未定义的行为)。
fp = fopen("%s", "r"); // very confused about this line; will this open the file?
不,不会。 它将打开名为%s
的文件。 你必须写
fp = fopen(file, "r");
代替。 不要假设您可以在无法使用的地方使用格式字符串。
varialble file
包含用户输入的文件名,因此请将其传递给fopen。 您所拥有的是格式字符串。
fp = fopen(file, "r");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.