我需要从 C++ 中的文件获取父目录:
例如:
输入:
D:\Devs\Test\sprite.png
输出:
D:\Devs\Test\ [or D:\Devs\Test]
我可以用一个函数来做到这一点:
char *str = "D:\\Devs\\Test\\sprite.png";
for(int i = strlen(str) - 1; i>0; --i)
{
if( str[i] == '\\' )
{
str[i] = '\0';
break;
}
}
但是,我只是想知道是否存在内置函数。 我使用 VC++ 2003。
如果您使用 std::string 而不是 C 风格的字符数组,则可以按以下方式使用 string::find_last_of 和 string::substr:
std::string str = "D:\\Devs\\Test\\sprite.png";
str = str.substr(0, str.find_last_of("/\\"));
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;
}
重型和跨平台方法是使用boost::filesystem::parent_path()。但显然这会增加您可能不希望的开销。
或者,您可以使用 cstring 的 strrchr 函数,如下所示:
include <cstring>
char * lastSlash = strrchr( str, '\\');
if ( *lastSlash != '\n') *(lastSlash +1) = '\n';
编辑 const 字符串是未定义的行为,因此声明如下:
char str[] = "D:\\Devs\\Test\\sprite.png";
您可以使用以下 1 种内衬来获得您想要的结果:
*(strrchr(str, '\\') + 1) = 0; // put extra NULL check before if path can have 0 '\' also
在 POSIX 兼容系统 (*nix) 上,有一个常用的函数用于此
dirname(3)
。在窗户上有 _splitpath
。
_splitpath 函数断开路径 分为四个部分。
void _splitpath(
const char *path,
char *drive,
char *dir,
char *fname,
char *ext
);
所以结果(这就是我认为你正在寻找的)将在
dir
。
这是一个例子:
int main()
{
char *path = "c:\\that\\rainy\\day";
char dir[256];
char drive[8];
errno_t rc;
rc = _splitpath_s(
path, /* the path */
drive, /* drive */
8, /* drive buffer size */
dir, /* dir buffer */
256, /* dir buffer size */
NULL, /* filename */
0, /* filename size */
NULL, /* extension */
0 /* extension size */
);
if (rc != 0) {
cerr << GetLastError();
exit (EXIT_FAILURE);
}
cout << drive << dir << endl;
return EXIT_SUCCESS;
}
在Windows平台上,您可以使用 PathRemoveFileSpec 或 PathCchRemoveFileSpec 为了达成这个。 但是,为了可移植性,我会采用此处建议的其他方法。
您可以使用 dirname 来获取父目录 检查此链接了解更多信息
拉古