2

I'm trying, in C, to get a string from user input so the program can open a chosen file.
I tried using fgets because I read on numerous threads that it is the safer option (as opposed to gets).
However when a string is stored using gets, the file opens, but with fgets it does not.

Here is the code I'm using:

char csvFile[256];
FILE *inpfile;

printf("Please enter CSV filename: ");
fgets(csvFile,256,stdin);

printf("\nFile is %s\n",csvFile);

inpfile = fopen(csvFile,"r");

if(inpfile == NULL)
{
    printf("File cannot be opened!");
}

I know the file exists but with fgets the if block is entered.
The only difference is that using:

gets(csvFile);

works in place of

fgets(csvFile,256,stdin);

Can anyone help me make sense of this? Thanks in advance.

james02
  • 97
  • 2
  • 8
  • 2
    [man fgets](http://linux.die.net/man/3/fgets) says: If a newline is read, ***it is stored into the buffer***. – fvu Aug 14 '14 at 15:13
  • possible duplicate of [Removing trailing newline character from fgets() input](http://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) – ani627 Sep 03 '14 at 10:15

3 Answers3

5

You need to remove the trailing newline:

char csvFile[256], *p;

fgets(csvFile, sizeof csvFile, stdin);
if ((p = strchr(csvFile, '\n')) != NULL) { 
    *p = '\0'; /* remove newline */
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

You can check the newline character at the end of csvFile by adding for example two "=" at the first and end of your sentence, respectively.

printf("\n=File is %s=\n",csvFile);

You can easily remove the newline character at the end of csvFile using strtok() function from <string.h> library. So you may need to add one line of code after reading the input string with fgets() in the following manner:

fgets(csvFile, sizeof csvFile, stdin);
strtok(csvFile, "\n");
  • 1
    This works well too, I do prefer it to Alter Mann's suggestion as it doesn't require a pointer declaration. Although both are valid. – james02 Aug 15 '14 at 10:43
  • 1
    @james02, The `strtok` function doesn't work as expected if the user enters an empty string (i.e. presses only Enter). It leaves the \n character intact, furthermore, uses a static buffer while parsing and is not thread-safe, [check this question](http://stackoverflow.com/q/2693776/1606345) – David Ranieri Aug 15 '14 at 12:27
0

The difference you observed between fgets and gets is that fgets leaves the newline character at the end of the read string. But it should not cause you to going back to gets - just remove the last character in csvFile if it is newline.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51