P.Wang P.Wang - 3 months ago 15
C++ Question

appending "../xx.txt" to the relative path does work in C++

I read some topics about relative path, but I've been wandering around them for hours without answer.
The code is like this:

std::string path = "./Debug/";
path.append("../hi.txt/");
std::ifstream inFile(path);
std::string str;
if (inFile.is_open())
{
inFile >> str;
std::cout << str << std::endl;
}
else
{
std::cout << "open failed" << std::endl;
}


This code will output:"open failed".
Any help would be appreciated.

Answer

When you put a / at the end of a path, it tells the system to execute it as a directory (i.e. list its contents). Since hi.txt is not a directory, you can't execute it as a directory and therefore it fails (assuming of course you didn't name a directory hi.txt).

To fix it: remove the /:

std::string path = "./Debug/" ;
path.append("../hi.txt") ;