Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file with user input (string) - C

Tags:

c

file

I'm trying to figure out how user input can be used as a filename in C. Here's the simple program I wrote.

#include <stdio.h>
#define MAX 100

int main()
{
    FILE *fp;
    char name[MAX];


    printf("Enter filename: ");
    fgets(name, MAX, stdin);

    if((fp = fopen(name, "w")) == 0)
        printf("File cannot be opened!");

    return 0;
}

It always prints "File cannot be opened".

like image 984
Arlind Avatar asked Jun 03 '26 08:06

Arlind


1 Answers

fgets retains the newline in the input.

like image 152
Matt Eckert Avatar answered Jun 05 '26 02:06

Matt Eckert