【发布时间】:2021-03-07 13:52:18
【问题描述】:
我正在尝试读取用户输入并打开用户输入的文件。我的程序似乎在 print 语句之后立即退出。任何帮助将不胜感激!
printf("What is the name of the file? \n");
scanf("%s", "fileName");
FILE* inFile = NULL;
inFile = fopen("fileName", "r");
if(inFile == NULL) {
printf("Could not open this file");
}
【问题讨论】:
-
从不在 scanf 中使用
"%s"作为转换说明符。这样做和使用gets一样糟糕。 -
总是检查scanf的返回值。
-
始终在您的错误消息中提供系统错误,并将错误消息写入 stderr。
if( inFile == NULL ) { perror(fileName); exit(EXIT_FAILURE);} -
根本不要使用
scanf(),直到您彻底了解其中的陷阱并知道为什么不应该使用它。声明一个足够大的数组,例如char line[1024];并读入if (fgets (line, sizeof line, stdin) == NULL) { /* handle EOF */ }行,现在只需使用line[strcspn (line, "\n")] = 0;从行尾修剪'\n'-- 完成。 -
请发minimal reproducible example,以便我们重现问题并帮助您调试。