如何读取用户选择的文本文件

问题描述 投票:0回答:1

如何创建一个文件指针,然后用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个回答
2
投票

去掉引号,这使它成为一个字符串文字,你需要实际的变量。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);
    }
    //...
}
© www.soinside.com 2019 - 2024. All rights reserved.