c - 如何从 C 中的用户输入正确读取文件?
问题描述
我正在尝试读取用户输入并打开用户输入的文件。我的程序似乎在 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
,但这完全是一个不同的问题)是:
scanf("%s", "fileName");
那应该是:
char fileName[128];
if( 1 == scanf("%127s", fileName)) ...
您不能写入字符串文字,因此将字符串文字的地址传递给 scanf 是一场等待发生的灾难。您确实应该使用 PATH_MAX 而不是硬编码的 128,但随后您需要使用 sprintf 来构造格式字符串,这似乎有损此示例。为了完整性:
#include <limits.h>
...
char fileName[PATH_MAX];
char fmt[64];
snprintf(fmt, sizeof fmt, "%%%ds", PATH_MAX - 1);
if( 1 == scanf(fmt, fileName) ){
FILE* inFile = fopen(fileName, "r");
if( inFile == NULL ){
perror(fileName);
exit(EXIT_FAILURE);
}
...
}
但请注意,您几乎肯定不想使用scanf
. 最好将其作为命令行参数并在argv
.
推荐阅读
- mysql - “Azure Database for MySQL 服务器”云服务是基于 Windows 还是 Linux 环境?
- javascript - axios 请求并行
- netlogo - 内存:在表中存储多个补丁的补丁变量
- spring - Spring / Reactor:检索和修改 Mono
- python - 如何使用 Cassandra API 将 Python 的 cosmos_client 连接到 Cosmos DB 实例?
- c++ - 如何在 CLion 中将外部 C++ 库与 Bazel 一起使用?
- c# - Google 跟踪代码管理器仅适用于特定版本的 IE11
- python - 通过 ssh 实时执行的流式 python 命令
- javascript - 在我的 Angular 项目中使用 @types/cleave.js 时如何忽略 TS1192?
- xamarin.forms - 为什么绝对导航 URL 不清除导航堆栈?