[英]Cannot find any files
I'm just starting out with C. In my program the user enters a file name and then I check if the file exists. 我刚刚开始使用C.在我的程序中,用户输入文件名,然后检查文件是否存在。
Here's the code so far: 这是迄今为止的代码:
printf("Enter the file name:\n");
char filename[50];
fgets(filename, 50, stdin);
printf("You have entered %s\n", filename);
if( access(filename, F_OK ) == -1 )
{
printf("File not found/access denied.\n");
}
In the same directory as the program itself I got a file named "steps". 在与程序本身相同的目录中,我得到了一个名为“steps”的文件。 However whenever I enter steps or ./steps or even ~/steps I get the file not found error message. 但是每当我输入步骤或./steps甚至〜/步骤时,我都会收到找不到文件的错误消息。
What's the issue here? 这是什么问题?
By the way I'm on Linux (Ubuntu). 顺便说一句,我在Linux(Ubuntu)上。 Also, I know for certain that I have access to the file - so it's not a matter of permissions. 此外,我确信我可以访问该文件 - 因此这不是权限问题。
fgets
includes the trailing New-Line in the buffer so access
thinks that is part of the file name. fgets
包含缓冲区中的尾随New-Line,因此access
认为它是文件名的一部分。 You need to strip off the New-Line. 你需要剥离新线。
After the fgets, add the following line: 在fgets之后,添加以下行:
if (filename[strlen(filename)-1] == '\n') filename[strlen(filename)-1] = '\0';
to strip it off. 脱掉它。
Edit: As @alk noted (thanks), this should be: 编辑:正如@alk所说(谢谢),这应该是:
if (strlen(filename) > 0 && filename[strlen(filename)-1] == '\n')
filename[strlen(filename)-1] = '\0';
&&
will not evaluate the right side if the left side evaluates to false
so there is no chance of going outside the array bounds. 如果左侧的计算结果为false
,则&&
不会评估右侧,因此没有机会超出数组范围。
Because fgets()
adds \\n
before null character. 因为fgets()
在空字符之前添加\\n
。
For example if you enter "abcd" this would become "abcd\\n" 例如,如果输入“abcd”,这将变为“abcd \\ n”
After reading file name, just replace \\n
with null character 读取文件名后,只需用空字符替换\\n
fgets(filename, 50, stdin);
if(filename[strlen(filename)-1]=='\n')
filename[strlen(filename)-1]='\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.