I'm trying to write a short bit of C code that will get a filename from the user, via the keyboard, and open the specified file, but I haven't been able to get fopen() to recognize the variable filename when I use fgets() to get it. Here's a snippet of the troublesome code:
#include <stdio.h>
#include <errno.h>
#define LINELEN 128
main() {
...
FILE *finptr;
char filename[LINELEN];
...
fgets(filename, LINELEN, stdin); /* Get the filename from the keyboard) */
if ((finptr = fopen(filename, "r")) == NULL) printf("Error in fopen: Error #%i\n", errno);
...
return 0}
I don't get any errer message when I compile, but when I run the code, I get the error message I defined in the if-statement:
Error in fopen: Error #2
If I use gets() instead of fgets(), the program works as expected. I am then able to read a line of text from the named file and display it on my monitor.
Apparently the return value from gets() differs in some way from the return value of fgets() -- enough to break the code as I've written it.
Any ideas what I'm doing wrong and how to fix it?