How do I ask the user for a filename to use as the input file?

this is my first post, so I hope I'm doing everything correctly. I've already searched google and this site, but I couldn't find the answer I was looking for.

I am trying to prompt the user for a file name and inputting this filename into fopen. When I try running and inputting an existing text file (with .txt extension), I still run into my filenotfound error message.

Here's my code so far (just trying to get the file open right now):

#include <stdio.h>
int c;
FILE *file;
char filename[99];
fgets(filename, 99, stdin);

file = fopen(filename, "r");

if (file) {
    while ((c = getc(file)) != EOF)
} else{
return 0;

I'm guessing it has something to do with me putting it into an array of chars? Is there some way to make a string out of them or is it something else?


fgets() retains the newline ( \n ). You need to remove it. One way to do that is to change:

fgets(filename, 99, stdin);


fgets(filename, 99, stdin);
char *p = strchr(filename, '\n'); // p will point to the newline in filename
if(p) *p = 0; // if p is not null, terminate filename at p

Need Your Help

SQL how to make null values come last when sorting ascending

sql sorting sql-order-by

I have a SQL table with a datetime field. The field in question can be null. I have a query and I want the results sorted ascendingly by the datetime field, however I want rows where the datetime f...