vie*_*ean 5 c++ dev-c++ visual-c++
我需要从C++中的文件中获取父目录:
例如:
输入:
D:\Devs\Test\sprite.png
Run Code Online (Sandbox Code Playgroud)
输出:
D:\Devs\Test\ [or D:\Devs\Test]
Run Code Online (Sandbox Code Playgroud)
我可以用一个函数做到这一点:
char *str = "D:\\Devs\\Test\\sprite.png";
for(int i = strlen(str) - 1; i>0; --i)
{
if( str[i] == '\\' )
{
str[i] = '\0';
break;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我只是想知道存在一个内置函数.我使用VC++ 2003.
提前致谢.
tha*_*ees 15
现在,使用 C++17 可以使用std::filesystem::path::parent_path:
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path p = "D:\\Devs\\Test\\sprite.png";
std::cout << "parent of " << p << " is " << p.parent_path() << std::endl;
// parent of "D:\\Devs\\Test\\sprite.png" is "D:\\Devs\\Test"
std::string as_string = p.parent_path().string();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*ine 12
如果您使用的是std :: string而不是C样式的char数组,则可以按以下方式使用string :: find_last_of和string :: substr:
std::string str = "D:\\Devs\\Test\\sprite.png";
str = str.substr(0, str.find_last_of("/\\"));
Run Code Online (Sandbox Code Playgroud)
编辑 const 字符串是未定义的行为,因此声明如下:
char str[] = "D:\\Devs\\Test\\sprite.png";
Run Code Online (Sandbox Code Playgroud)
您可以使用以下 1 种内衬来获得您想要的结果:
*(strrchr(str, '\\') + 1) = 0; // put extra NULL check before if path can have 0 '\' also
Run Code Online (Sandbox Code Playgroud)