将"../xx.txt"追加到相对路径确实适用于C++

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

本文关键字:路径 适用于 C++ 相对 xx txt 追加      更新时间:2023-10-16

我读了一些关于相对路径的主题,但我已经徘徊了几个小时没有答案。代码如下:

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;
}

这段代码将输出:"open failed"。

当您将/放在路径的末尾时,它告诉系统将其作为目录执行(即列出其内容)。由于hi.txt不是一个目录,因此您不能将其作为目录执行,因此它会失败(当然假设您没有将目录命名为hi.txt)。

修复方法:移除/:

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