fgets 函数最后打印垃圾

fgets function printing garbage at the end

我制作了一个程序,可以创建一个文件,该文件的名称由用户指定。

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main()
{
       int g;
       char file[15];
       fgets(file,15,stdin);
       g=open(file,O_CREAT | O_WRONLY,__S_IWRITE);


}

但它创建的文件的文件名末尾有一些垃圾字符。我该如何纠正?

这里是示例 运行:

$ ./a.out
coolfile.txt
$ ls
a.out  coolfile.txt?  test.c

相同的程序,但仅使用 gets 函数即可提供正确的文件名,但我听说不应使用 gets。

fgets() 将换行符存储在结果中每行的末尾。因此,您正在创建名称以换行符结尾的文件。要修复它,只需检查最后一个字符并将其设置为 '[=11=]'(如果它是 '\n')。

fgets 在每行的末尾存储 \n 因此你需要删除 \n

点此使用 strcspn 函数

因此您的代码应如下所示

 #include <stdlib.h>
 #include <stdio.h>
 #include <fcntl.h>
 #include <string.h>
 int main()
  {
    int g;
    char file[15];
    fgets(file,15,stdin);
    file[strcspn(file, "\n")] = 0;
    g=open(file,O_CREAT | O_WRONLY,__S_IWRITE);
  }

您可以在 :- https://www.tutorialspoint.com/c_standard_library/c_function_strcspn.htm

上查看有关 strcspn 的更多信息

另请参阅:- Removing trailing newline character from fgets() input