如何读取用户选择的文本文件
How to read text file selected by the user
如何创建文件指针,然后从用户使用 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");
删除引号,使其成为字符串文字,您需要存储文件名称的实际变量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);
}
//...
}
如何创建文件指针,然后从用户使用 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");
删除引号,使其成为字符串文字,您需要存储文件名称的实际变量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);
}
//...
}