【问题标题】:When using gets to get a file name in C, the file opens but when using fgets it does not在 C 中使用 get 获取文件名时,文件会打开,但使用 fgets 时,文件不会打开
【发布时间】:2014-08-14 15:11:25
【问题描述】:

我正在尝试在 C 中从用户输入中获取字符串,以便程序可以打开选定的文件。
我尝试使用 fgets,因为我在许多线程上读到它是更安全的选择(而不是 gets)。
但是,当使用gets 存储字符串时,文件会打开,但使用fgets 则不会。

这是我正在使用的代码:

char csvFile[256];
FILE *inpfile;

printf("Please enter CSV filename: ");
fgets(csvFile,256,stdin);

printf("\nFile is %s\n",csvFile);

inpfile = fopen(csvFile,"r");

if(inpfile == NULL)
{
    printf("File cannot be opened!");
}

我知道该文件存在,但使用 fgets 输入了 if 块。
唯一的区别是使用:

gets(csvFile);

代替

fgets(csvFile,256,stdin);

谁能帮我理解这一点? 提前致谢。

【问题讨论】:

标签: c file fopen


【解决方案1】:

您需要删除尾随的换行符:

char csvFile[256], *p;

fgets(csvFile, sizeof csvFile, stdin);
if ((p = strchr(csvFile, '\n')) != NULL) { 
    *p = '\0'; /* remove newline */
}

【讨论】:

  • 所以基本上得到指向字符串中'\n'的指针,然后改变那个地址的值?
  • 当然还有 csvFile[strlen(csvFile)-1] = '\0';
【解决方案2】:

您可以检查csvFile 末尾的换行符,例如分别在句子的开头和结尾添加两个“=”。

printf("\n=File is %s=\n",csvFile);

您可以使用<string.h> 库中的strtok() 函数轻松删除csvFile 末尾的换行符。所以你可能需要在读取fgets()的输入字符串后添加一行代码,方式如下:

fgets(csvFile, sizeof csvFile, stdin);
strtok(csvFile, "\n");

【讨论】:

  • 这也很好用,我更喜欢 Alter Mann 的建议,因为它不需要指针声明。虽然两者都是有效的。
  • @james02,如果用户输入空字符串(即仅按 Enter),strtok 函数将无法按预期工作。它使 \n 字符保持不变,此外,在解析时使用静态缓冲区并且不是线程安全的,check this question
【解决方案3】:

您在fgetsgets 之间观察到的区别是fgets 在读取字符串的末尾留下换行符。但它不应该让你回到gets - 如果它是换行符,只需删除csvFile 中的最后一个字符。

【讨论】:

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