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?

Recommended Answers

All 2 Replies

>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.

fgets() reads and include the enter key to the string, you need to remove it.
Maybe something like:

if ( fgets(filename, sizeof filename, stdin) )
{
    len = strlen(filename) -1; /* position before '\0' */
    /* if it's a new line remove it */
    if ( filename[len] == '\n')
        filename[len] = '\0';
}

gets() doesn't include the new line.

Forget that gets() exists.

That was it -- thank you, Aia!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.