C语言 如何使用fopen打开当前目录中文件夹内的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29561474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:50:41  来源:igfitidea点击:

How to open file inside folder in current directory using fopen

cfopen

提问by MonkeyImpala

I want to open a file that is inside a folder in the current working directory like so:

我想打开当前工作目录中文件夹内的文件,如下所示:

fopen("/folder/file.txt","r");

I'm unable to do so in this way, i get a "No such file or directory" error.

我无法以这种方式这样做,我收到“没有这样的文件或目录”错误。

How can i do this properly?

我怎样才能正确地做到这一点?

Thank you in advance for any help.

预先感谢您的任何帮助。

回答by Karthikeyan.R.S

You have to mention that is a current directory. Try this,

你必须提到这是一个当前目录。尝试这个,

fopen("./folder/file.txt","r");

Or

或者

fopen("folder/file.txt","r");

If you mentioning like this /folder/file.txtit will search the directory from the root directory. So this is the reason for getting the error.

如果您这样提及/folder/file.txt,它将从根目录搜索目录。所以这就是得到错误的原因。

回答by David Ranieri

Try:

尝试:

fopen("./folder/file.txt","r"); /* dot means the directory itself */

or

或者

fopen("folder/file.txt","r"); /* without the first backslash */

回答by MonkeyImpala

It seems that if i remove the first backslash it works.

看来,如果我删除第一个反斜杠,它就可以工作。

Like so:

像这样:

fopen("folder/file.txt","r");

fopen("文件夹/文件.txt","r");

weird.

奇怪的。