11

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

and I found it in

/home/user/code/Project/build/source/Project/components/Project/test/findme.dat

so I created the relative path

/../../../../../../source/Project/components/Project/test/file.dat

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.

Can you help me?

IndustProg
  • 627
  • 1
  • 13
  • 33
Peter111
  • 803
  • 3
  • 11
  • 21
  • What is the current working directory of your program? The path you provide has to be relative to the CWD. Also, since you start the path with `/` that means you start *at the root*, and since there is no parent directory for the root that means `/..` is the same as `/`, leading to your path being equal to `/source/Project/components/Project/test/file.dat` – Some programmer dude Mar 10 '16 at 07:22
  • It all depends on current working directory. i.e where your program is placed. – usamazf Mar 10 '16 at 07:23
  • Your 'relative' path is not relative. It should start with a dot instead of a slash. e.g ./../../../../../../source/Project/components/Project/test/file.dat – George Michael Mar 10 '16 at 07:23
  • Thanks guys, you helped a lot! – Peter111 Mar 10 '16 at 07:34
  • **Update: For c++ 17+:** https://en.cppreference.com/w/cpp/filesystem/path – Andrew Apr 10 '22 at 01:20

1 Answers1

18

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

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

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

or if it is in some other folder within Project folder you can do something like this:

../test/file.dat

../ take you to the parent of your current code directory which under this case's assumption is Project.

usamazf
  • 3,195
  • 4
  • 22
  • 40