Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在fopen()函数中使用和输入用户作为参数?_C_Input_Fopen - Fatal编程技术网

C 如何在fopen()函数中使用和输入用户作为参数?

C 如何在fopen()函数中使用和输入用户作为参数?,c,input,fopen,C,Input,Fopen,我试图用fopen编写一段代码,在给定模式下打开一个文件,但我希望用户能够告诉程序他要打开的文件的名称或路径,但编译器对我喊道,我编写的代码如下: printf("Path/Name of the file: \n"); char input_user = getchar(); filePointer = fopen(input_user, "r"); 编译器返回的错误如下:“警告:传递'fopen'的参数1将从整数生成指针,而不进行强制转换[-Wint转换] filePointer=fop

我试图用fopen编写一段代码,在给定模式下打开一个文件,但我希望用户能够告诉程序他要打开的文件的名称或路径,但编译器对我喊道,我编写的代码如下:

printf("Path/Name of the file: \n");
char input_user = getchar();

filePointer = fopen(input_user, "r");
编译器返回的错误如下:“警告:传递'fopen'的参数1将从整数生成指针,而不进行强制转换[-Wint转换] filePointer=fopen(输入用户,“r”);”

这是:“注意:应为'const char*restrict',但参数的类型为'char' extern FILE*fopen(const char*\uuuu restrict\uu filename,“

如”所述,fopen接受一个字符*(指向字符的指针),而不是一个字符。使用数组也可以,正如他所说的那样

我将把他的评论整理成一个答案

#include <stdio.h>

int main()
{
    printf("Path/Name of the file: \n");
    char filename[128];
    scanf("%127s", filename);

    FILE *filePointer = fopen(filename, "r");
    return 0;
}

我希望您能更好地理解错误所在,并且这已经足够清楚了!

fopen
希望它的第一个参数是
char*
类型。您正在传递一个
char
。您传递一个以null结尾的字符串作为要打开的文件名。单个字符不是字符串。因此,如果我只写“char*input\u user=getchar”(谢谢回答)另一个相关且非常重要的注意事项是:在未验证字符串的情况下,不要使用用户输入打开文件。用户输入的任何内容都可能导致程序出现安全问题。或者最好的情况是崩溃(拒绝服务)。读取单个字符,您不能简单地将此单个字符视为字符串。您可能需要类似于
char filename[128];scanf(“%127”,filename);
expected ‘const char * restrict’ but argument is of type ‘char’