Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 377
Peter111 Avatar asked Mar 10 '16 07:03

Peter111


People also ask

How do I open a file with relative path?

Opening a File with Relative Path In the relative path, it will look for a file into the directory where this script is running. # Opening the file with relative path try: fp = open("sample. txt", "r") print(fp. read()) fp.

What is relative path in C?

A relative path is a way to specify the location of a directory relative to another directory. For example, suppose your documents are in C:\Sample\Documents and your index is in C:\Sample\Index. The absolute path for the documents would be C:\Sample\Documents.

What is C$ in Windows path?

If it's a Windows system, the $ represents a hidden or administrative share. This is typically setup either by default ("C$" is the standard share for the C drive), or to obscure the shared folder so that it is not programmatically found or easy to access by unwanted users.

How do I read a file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);


1 Answers

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.

like image 106
usamazf Avatar answered Oct 15 '22 00:10

usamazf