将“../xx.txt”附加到相对路径在 C++ 中确实有效
appending "../xx.txt" to the relative path does work in C++
我读了一些关于相对路径的话题,但我已经在它们周围徘徊了几个小时而没有得到答案。
代码是这样的:
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") ;
我读了一些关于相对路径的话题,但我已经在它们周围徘徊了几个小时而没有得到答案。 代码是这样的:
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") ;