When using gets to get a file name in C, the file opens but when using fgets it does not

耗尽温柔 提交于 2020-01-10 05:34:04

问题


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.


回答1:


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 */
}



回答2:


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");



回答3:


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.



来源:https://stackoverflow.com/questions/25311542/when-using-gets-to-get-a-file-name-in-c-the-file-opens-but-when-using-fgets-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!