2

I have some demo code that wants the user to input a filename and the mode. The book is suggesting the dreaded gets(); function for input, which I refuse to use, so I tried to grab my input with fgets(). When I used fgets() I specified my input stream as 'stdin', however the code will not work. The code WILL work with gets(), however. I assume that the problem with my implementation of fgets() is the 'stdin' stream type. Is that why my fgets() will not work with this program? If so, what input stream type should I use? Here is the program:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    char ch, filename[40], mode[4];

    while(1)
    {
        printf("\nEnter a filename: "); //This is where fgets/gets conflict is
        //fgets(filename, 30, stdin);     //I commented out the fgets()
        gets(filename);
        printf("\nEnter a mode (max 3 characters):");
        //fgets(mode, 4, stdin);                      //fgets again
        gets(mode);
        //Try to open the file
        if((fp = fopen(filename, mode)) != NULL)
        {
            printf("\nSuccessful opening %s in mode %s.\n",
                filename, mode);
            fclose(fp);
            puts("Enter x to exit, any other to continue.");
            if((ch = getc(stdin)) == 'x')
            {
                break;
            }else{
                continue;
            }
        }else
        {
            fprintf(stderr, "\nError opening file %s in mode %s.\n",
                filename, mode);
            puts("Enter x to exit, any other to try again.");
            if((ch = getc(stdin)) == 'x')
            {
                break;
            }else{
                continue;
            }
        }

}   
return 0;
}

Thanks in advance all. This program was from "Teach Yourself C in 21 Days" by B. Jones.

1 Answers1

4

Well done on not wanting to use gets(); that is absolutely the correct way to go.

The error opening the file arises from the fact that fgets() keeps the newline and gets() does not. When you try to open the file name with the newline, the file is not found.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278