首页 > 解决方案 > 如何从 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");
  }

标签: cfileinputfile-io

解决方案


你问题的根源(正在使用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.


推荐阅读