当使用获得在C获取文件名,文件打开,但使用与fgets当它不 [英] When using gets to get a file name in C, the file opens but when using fgets it does not

查看:215
本文介绍了当使用获得在C获取文件名,文件打开,但使用与fgets当它不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,在C,从用户输入得到一个字符串,所以程序可以打开所选文件。
结果我尝试使用与fgets因为我在多个线程读取,它是更安全的选择(而不是获取)。
结果然而,当一个字符串使用得到,文件打开存储,但与fgets它没有。

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.

下面是code我使用的是:

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

我知道文件存在,但用于fgets进入if块。结果
唯一的区别在于,使用:

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

gets(csvFile);

作品代替

fgets(csvFile,256,stdin);

谁能帮我理解这一点?
先谢谢了。

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

推荐答案

您需要删除尾随的换行符:

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

这篇关于当使用获得在C获取文件名,文件打开,但使用与fgets当它不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆