如何在C ++中打开具有相对路径的文件? [英] How to open a file with relative path in C++?
问题描述
我现在正在编写测试用例,并创建了一些尝试读取的测试文件.绝对路径为:
I am writing test cases right now and I created some test files which I try to read. The absolute path is:
/home/user/code/Project/source/Project/components/Project/test/file.dat
但是出于显而易见的原因,使用绝对路径进行测试是不好的.因此,我尝试将绝对路径转换为相对路径,但我不知道为什么它不起作用.我用相对路径
but testing with an absolute path is bad for obvious reasons. So I try to convert the absolute path into a relative one and I don't know why it doesn't work. I created a file with the relative path
findme.dat
我在
/home/user/code/Project/build/source/Project/components/Project/test/findme.dat
所以我创建了相对路径
/../../../../../../source/Project/components/Project/test/file.dat
,但文件未打开且未与is
对象相关联,
std::ifstream is (path);
,并且is.is_open()
函数返回fulse.
but the file is not open and not associated with the is
object,
std::ifstream is (path);
, and the is.is_open()
function returns fulse.
你能帮我吗?
推荐答案
您所使用的根本不是相对路径.确定使用的是相对路径语法,而不是实际含义.
What you are using is not at all a relative path. Sure you are using the relative path syntax but not the actual meaning of what it is.
/../../../../../../source/Project/components/Project/test/file.dat
/../../../../../../source/Project/components/Project/test/file.dat
此路径以/开头,表示root,然后找到它的父级,由于root没有父级并继续运行,因此它再次返回root.
This path starts with a / which means root then finds it parent which return root again since root has no parent and goes on... The simplified version of this is:
/source/Project/components/Project/test/file.dat
/source/Project/components/Project/test/file.dat
因此它将在根目录中查找当然不存在的文件夹源.
So it will look for folder source in root which of-course doesn't exist.
您应该做的是这样的(假设您的代码在项目文件夹中):
What you should do is something like this (assuming your code is in project folder):
./test/file.dat
./test/file.dat
,或者如果它位于Project文件夹中的其他文件夹中,则可以执行以下操作:
or if it is in some other folder within Project folder you can do something like this:
../test/file.dat
../test/file.dat
../带您到当前代码目录的父目录,在这种情况下,该目录为Project.
../ take you to the parent of your current code directory which under this case's assumption is Project.
这篇关于如何在C ++中打开具有相对路径的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!