c 如何从路径字符串中删除文件名

新手上路,请多包涵

我有

const char *pathname = "..\somepath\somemorepath\somefile.ext";

如何将其转换为

"..\somepath\somemorepath"

?

原文由 Mat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 773
2 个回答

最简单的方法是使用 find_last_of 成员函数 std::string

 string s1("../somepath/somemorepath/somefile.ext");
string s2("..\\somepath\\somemorepath\\somefile.ext");
cout << s1.substr(0, s1.find_last_of("\\/")) << endl;
cout << s2.substr(0, s2.find_last_of("\\/")) << endl;

此解决方案适用于正斜杠和反斜杠。

原文由 Sergey Kalinichenko 发布,翻译遵循 CC BY-SA 3.0 许可协议

假设您可以访问 c++17,它应该是这样的:

 std::filesystem::path fullpath(path_string);
fullpath.remove_filename();
cout << fullpath.string();

如果你没有 c++17,但可以访问 boost,你可以用 boost::filesystem::path 做同样的事情。

使用这些库之一具有与多个操作系统兼容的优点。

原文由 John Bowers 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题