fgets在用户输入中引入新行

时间:2014-09-02 11:06:46

标签: c string file fgets

我正在提示用户输入文件名,但是一旦用户按下回车键,它也会进入文件名。所以永远找不到文件。

int main (){
char file[100];
FILE *fp;

printf("Please enter a valid filename:\n");
fgets(file,100,stdin);
fp=fopen(file, "r");

if(!fp){
printf("File not found.\n"); \\This will always happen because a new line is added to the user's input.
return 1;}

如果我使用

scanf("%s", file);

问题没有发生,但我听说scanf不是一个好用的功能,会引入新的问题。如何解决fgets的新线问题?

2 个答案:

答案 0 :(得分:2)

fgets(file,100,stdin);之后,执行此操作file[strlen(file)-1]='\0';,它会从代码中删除\n。要使用strlen()功能,您需要在代码中加入string.h

尝试修改后的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (){

    char file[100];
    FILE *fp;

    printf("Please enter a valid filename:\n");

    fgets(file,100,stdin);
    file[strlen(file)-1]='\0'; //Removing \n from input
    fp=fopen(file, "r");

    if(fp==NULL)
    {
        printf("File not found.\n");
        return 1;
    }
    else
    {
        printf("File found!\n");
        fclose(fp);
        return 0;
    }
}

答案 1 :(得分:-2)

fgets()返回\ n新行代码....这就是它的作用。你必须消灭那个角色。

鉴于溢出或至少完全填充,传入缓冲区是一种流行的攻击向量,我更喜欢防御此类攻击的代码。

char *cp;
file[(sizeof file)-1)] = '\0'; /* assure \0 termination on buffer fill attack */
cp = strchr( file, '\n' );     /* find expected \n, but allow for none */
if ( cp ) *cp = '\0';          /* safely clear closing \n */