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.
The difference you observed between
fgets
andgets
is thatfgets
leaves the newline character at the end of the read string. But it should not cause you to going back togets
- just remove the last character incsvFile
if it is newline.You need to remove the trailing newline:
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.You can easily remove the newline character at the end of
csvFile
usingstrtok()
function from<string.h>
library. So you may need to add one line of code after reading the input string withfgets()
in the following manner: