C – 如何提示用户输入文件名

C编程很新。 我正在编写一个程序,我想提示用户输入要打开的文件名以供阅读。 在我显示的代码下面我想抛出错误,如果它没有打开或文件不存在,但是当我运行它时,我的代码爆炸,我必须关闭程序(DOS)

/*ask user for the name of the file*/ printf("enter file name: "); gets(fname); //Opens the file from where the text will be read. fp=fopen(fname, "r"); //Checks if the file us unable to be opened, then it shows the error message if (fp == NULL) { printf("\nError, Unable to open the file for reading\n"); } 

//您可以通过创建name.txt文件来测试它。 如果您需要其他信息,请与我们联系。

好吧,你应该确保fname有足够的空间来存储你的文件名,否则你几乎肯定会导致腐败和“炸毁”:-)

例如,以下代码段:

 char fname[10]; gets (fname); 

如果您输入的信息比fname可以容纳的信息多,则会出现问题。 那时,你进入了未定义的行为区域, 任何事情都可能发生。

但是,因为gets无法限制用户输入的内容,所以你永远不应该使用它!

在这个答案中可以找到一个适当的,受保护的用户输入方法。

它使用fgets因为它可以限制用户输入的内容。 它还允许提示,在出现问题时提供错误指示,正确处理文件结尾,并删除任何过大行的剩余部分,以便它不会影响下一个输入操作。

事实上,我会在这里复制它以使这个答案自成一体:

 #include  #include  #define OK 0 #define NO_INPUT 1 #define TOO_LONG 2 static int getLine (char *prmpt, char *buff, size_t sz) { int ch, extra; // Get line with buffer overrun protection. if (prmpt != NULL) { printf ("%s", prmpt); fflush (stdout); } if (fgets (buff, sz, stdin) == NULL) return NO_INPUT; // If it was too long, there'll be no newline. In that case, we flush // to end of line so that excess doesn't affect the next call. if (buff[strlen(buff)-1] != '\n') { extra = 0; while (((ch = getchar()) != '\n') && (ch != EOF)) extra = 1; return (extra == 1) ? TOO_LONG : OK; } // Otherwise remove newline and give string back to caller. buff[strlen(buff)-1] = '\0'; return OK; } 

您可以按如下方式调用它,指定缓冲区和大小,并在返回时接收错误指示:

 // Test program for getLine(). int main (void) { int rc; char buff[10]; rc = getLine ("Enter string> ", buff, sizeof(buff)); if (rc == NO_INPUT) { // Extra NL since my system doesn't output that on EOF. printf ("\nNo input\n"); return 1; } if (rc == TOO_LONG) { printf ("Input too long [%s]\n", buff); return 1; } printf ("OK [%s]\n", buff); return 0; } 

不确定你错过了什么,但是这个程序在命令行上使用cl.exe编译并运行。

 #include  #include  #include  int main(){ char fname[100]; FILE* fp; memset(fname, 0, 100); /*ask user for the name of the file*/ printf("enter file name: "); gets(fname); //Opens the file from where the text will be read. fp = fopen(fname, "r"); //Checks if the file us unable to be opened, then it shows the error message if (fp == NULL) { printf("\nError, Unable to open the file for reading\n"); } } 

另请注意,某些编译器(包括Microsoft)要求您在使用默认选项调用时将所有声明放在函数的顶部。

好吧,这就是我发生的事情,为“if”添加了“else”条件。下面提到的是代码。

 #include #include #include int main() { char fname[100]; FILE* fp; memset(fname, 0, 100); /*ask user for the name of the file*/ printf("enter file name: "); gets(fname); fp = fopen(fname, "r"); //Checks if the file us unable to be opened, then it shows the error message if (fp == NULL) { printf("\nError, Unable to open the file for reading\n"); } else { printf("hello"); } getch(); } 

还要确保已添加“#include”作为头文件。