C fgets函数在末尾打印垃圾

C fgets函数在末尾打印垃圾,c,fgets,C,Fgets,我制作了一个程序,用用户给定的名称创建一个文件 #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); } 同一个程序只使用gets函数给出

我制作了一个程序,用用户给定的名称创建一个文件

#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);


}

同一个程序只使用gets函数给出了正确的文件名,但我听说不应该使用gets。

fgets()
将换行符存储在结果中每一行的末尾。因此,您正在创建名称以换行符结尾的文件。要修复它,只需检查最后一个字符并将其设置为
'\0'
,如果它是
'\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);
  }
#包括
#包括
#包括
#包括
int main()
{
int g;
字符文件[15];
fgets(文件15,标准DIN);
文件[strcspn(文件“\n”)]=0;
g=打开(文件,O|u创建| O|u WRONLY,uu S_IWRITE);
}
有关strcspn的更多信息,请参见:-


另请参阅:-

目前,代码中没有对写入函数的调用,请向我们显示文件的内容。此外,打开文件描述符后,应始终关闭文件描述符。
fgets()
保留
'\n'
。该字符可能是可打印文件的问题names@PhilippGrassl文件为空。我使用了cat命令add
#include
,然后只使用了
fgets(File,sizeof File,stdin);尺寸长度=标准长度(文件);如果(len&&file[len-1]='\n')file[--len]=0将用nul终止字符(
'\0'
或简单等效的“0”)覆盖任何
'\n'
。的可能重复项
 #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);
  }