【问题标题】:How to read text file selected by the user如何读取用户选择的文本文件
【发布时间】:2020-06-10 19:59:00
【问题描述】:

如何创建文件指针,然后从用户使用 scanf 选择的输入文件中读取?

输入文件 input.txt 已经在项目文件夹中。

这是我写的,但我对如何根据用户输入读取文件感到困惑。 我知道ifp = fopen("input.txt", "r"); 会读取该文件,所以我的问题是如何询问用户需要读取什么文件,然后使用该信息读取正确的文件?

FILE *ifp;

char filename[] = {0}; 

ifp = filename;    

printf("Please enter the name of the file.\n");
scanf("%s", filename);    

ifp = fopen("filename", "r");

【问题讨论】:

    标签: c arrays file-io


    【解决方案1】:

    删除引号,使其成为字符串文字,您需要存储文件名的实际变量filename

    filename 也应该有足够的大小来容纳文件名:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
    
        FILE *ifp;
        char filename[50]; //50 char buffer
    
        printf("Please enter the name of the file.\n");
        scanf("%49s", filename); //%49s limits the size to the container, -1 for null terminator
    
        ifp = fopen(filename, "r"); //<-- remove quotes
    
        //checking for file opening error
        if(ifp == NULL) {
            perror("fopen");
            return(EXIT_FAILURE);
        }
        //...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多