C++98获取路径父目录
在C++98中,可以使用以下方法获取路径的父目录:
#include <iostream>
#include <string>
std::string getParentDirectory(const std::string& path) {
std::size_t found = path.find_last_of("/\\");
if (found != std::string::npos) {
return path.substr(0, found);
}
return "";
}
int main() {
std::string path = "C:/Users/John/Documents/file.txt";
std::string parentDir = getParentDirectory(path);
std::cout << parentDir << std::endl;
return 0;
}
以上代码中,getParentDirectory()函数接受一个路径字符串作为参数,使用find_last_of()函数找到最后一个路径分隔符的位置,并使用substr()函数提取父目录部分,然后返回该父目录字符串。
在主函数中,我们使用示例路径"C:/Users/John/Documents/file.txt"来测试getParentDirectory()函数,并将结果打印输出。
输出结果为:"C:/Users/John/Documents",即为路径的父目录
原文地址: https://www.cveoy.top/t/topic/iF8n 著作权归作者所有。请勿转载和采集!