问题描述
|
例如,我有字符串
\"root/data/home/file1.txt\"
,我想得到\"root/data/home\"
。C++中是否有一个方便的函数可以执行此操作,还是应该自己编写?
解决方法
您可以进行基本的字符串操作,即
std::string path = \"root/data/home/file1.txt\";
// no error checking here
std::string prefix = path.substr(0,path.find_last_of(\'/\'));
或采用Boost.Filesystem之类的第三个选项:
namespace fs = boost::filesystem;
fs::path path = \"root/data/home/file1.txt\";
fs::path prefix = path.parent_path();
, 如果您使用的是POSIX系统,请尝试dirname(3)。
, 语言本身当然没有方便的功能。字符串库提供了find_last_of,它应该做得很好。
, 这是相当依赖平台的。例如,Windows使用(4)作为路径分隔符(大多数情况下),Unix使用(5),而MacOS(OSX之前的版本)使用(6)。
Windows特定的API是“ 7”。