因此,我尝试根据用户输入打开一个文件,但我只是不断获取我输入的内容。
这就是我所拥有的。
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE* data;
char a[144];
printf("Enter a filename:\n");
fscanf(stdin, "%143[^\t]", a);
data = fopen(a, "r");
printf("%s", a);
fclose(data);
return 0;
}
这是我的文本文件。
larry snedden 123 mocking bird lane
sponge bob 321 bikini bottom beach
mary fleece 978 pasture road
hairy whodunit 456 get out of here now lane
最佳答案
您面临三个主要问题:(1) 您使用 fscanf(stdin, "%143[^\t]", a);
从用户处获取文件名,该文件名将读取除 tab
之外的所有字符(包括按 Enter 生成的尾随 '\n'
),(2)打开用户输入的文件并将 fopen
的返回值分配给 data
后,您无法知道该文件是否实际打开(鉴于文件名中包含尾随的 '\n'
,我怀疑它失败了); (3) 您从未真正从文件流 data
中读取内容(这可能是一件好事,因为您未能验证它实际上是打开的。
关键是要验证程序中的每个关键步骤尤其是用户输入的每一点。每个函数都提供一个返回值——使用它们来验证函数是否成功或失败。
一个添加验证的简短示例(并在需要时声明一个常量 - 除非绝对需要,否则不要在代码中使用魔数(Magic Number) - 就像 scanf
field-width 修饰符),例如
#include <stdio.h>
#define MAXC 1024 /* if you need a constant, define one (or more)
( don't SKIMP on buffer size ) */
int main (void)
{
FILE* data = NULL; /* initialize all variables */
size_t nlines = 0;
char a[MAXC] = "";
printf("Enter a filename: ");
/* VALIDATE EVERY SINGLE BIT OF INPUT */
if (fscanf (stdin, " %1023[^\n]", a) != 1) {
fputs ("user canceled input.\n", stderr);
return 1;
}
/* open/VALIDATE file open for reading */
if ((data = fopen (a, "r")) == NULL) {
perror ("fopen-a");
return 1;
}
printf ("file opened: %s\n\n", a);
/* reuse buffer to read each line */
while (fgets (a, MAXC, data) != NULL)
/* fgets include '\n' in buffer if buffer of sufficient size */
printf ("line[%3zu]: %s", nlines++ + 1, a);
fclose(data);
return 0;
}
输入文件示例
$ cat dat/file.txt
larry snedden 123 mocking bird lane
sponge bob 321 bikini bottom beach
mary fleece 978 pasture road
hairy whodunit 456 get out of here now lane
示例使用/输出
$ ./bin/fopen_file_from_user
Enter a filename: dat/file.txt
file opened: dat/file.txt
line[ 1]: larry snedden 123 mocking bird lane
line[ 2]: sponge bob 321 bikini bottom beach
line[ 3]: mary fleece 978 pasture road
line[ 4]: hairy whodunit 456 get out of here now lane
关于c - 如何获取用户输入以在 C 中打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566888/