Search code examples
cstringfilefgets

fgets Introducing new line in user's input


I'm prompting the user for the file name, but once the user presses enter, it takes that into the file name as well. so the file is never found.

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;}

If I use

scanf("%s", file);

The issue doesn't happen, but I heard scanf is not a good function to use and would introduce new issues. How can I solve the new line problem with fgets?


Solution

  • After fgets(file,100,stdin);, do this file[strlen(file)-1]='\0';, it will remove \n from the code. To use strlen() function you need to include string.h in your code.

    Try this modified code:

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