C++ fopen 相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24596979/
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
C++ fopen relative Path
提问by K?ptn Freiversuch
I read through some topic about relative path, but i still got i wrong. I hope sb can help me :). I am using Visual studio 2013, windows 7
我通读了一些关于相对路径的主题,但我还是弄错了。我希望某人可以帮助我:)。我使用的是 Visual Studio 2013,Windows 7
I got the following directories:
我得到以下目录:
Here is my .exe file D:\uni\c++\ex5\msvc2013\ex5\Debug
这是我的 .exe 文件 D:\uni\c++\ex5\msvc2013\ex5\Debug
Here is the file i want to read D:\uni\c++\ex5\res\thehead.raw
这是我要读取的文件 D:\uni\c++\ex5\res\thehead.raw
The code for opening the file:
打开文件的代码:
FILE* f;
f = fopen("..\..\..\res\thehead.raw", "rb");
if (f == NULL)
printf("FAIL!!");
As i need to use relative paths i figured it out as following: ..\ gets to parent directory.
因为我需要使用相对路径,所以我想通如下:..\ 到达父目录。
so "..\..\..\" should get me into the folder "D:\uni\c++\ex5\".
所以“..\..\..\”应该让我进入文件夹“D:\uni\c++\ex5\”。
\res should open the res foulder.
\res 应该打开 res 文件夹。
Needless to say it fails and i have no idea why. Any help would be appreciated.
不用说它失败了,我不知道为什么。任何帮助,将不胜感激。
采纳答案by localhost
@K?ptn With some modifications to the code, due to some warnings encountered, I found the following worked, although I used the C drive and not D drive as my system does not have a D drive. Effectively, the following code works same and my system will have the "file opened" message that I have added. I find this works the same whether it is run through the debugger, or executed directly from the executable in the Debug folder.
@K?ptn 对代码进行了一些修改,由于遇到了一些警告,我发现以下方法有效,尽管我使用的是 C 盘而不是 D 盘,因为我的系统没有 D 盘。实际上,以下代码的工作原理相同,我的系统将显示我添加的“文件已打开”消息。我发现无论是通过调试器运行还是直接从 Debug 文件夹中的可执行文件执行,它的工作原理都是一样的。
Paths
路径
Here is my .exe file C:\uni\c++\ex5\msvc2013\ex5\Debug
Here is the file i want to read C:\uni\c++\ex5\res\thehead.raw
Source Code
源代码
#include <iostream>
int main (int argc, char ** argv)
{
FILE* f;
fopen_s(&f, "..\..\..\res\thehead.raw", "rb");
if (f == NULL)
{
printf("FAIL!!");
}
else
{
printf("File opened.");
}
return 0;
}
回答by user4815162342
Relative paths are relative to the current working directory, not the path of the executable. The current working directory is the directory from which you started the program.
相对路径是相对于当前工作目录的,而不是可执行文件的路径。当前工作目录是您从中启动程序的目录。
To calculate a path relative to the position of the executable, the simplest option is to access the executable as argv[0]
, extract the directory, and chdir()
into it.
要计算相对于可执行文件位置的路径,最简单的选择是访问可执行文件 as argv[0]
,提取目录并chdir()
进入其中。