从c++文件中获取父目录
visual Get parent directory from file in C++
我需要从c++文件中获取父目录:
例如:输入:D:DevsTestsprite.png
输出:D:DevsTest [or D:DevsTest]
我可以用一个函数来完成:
char *str = "D:\Devs\Test\sprite.png";
for(int i = strlen(str) - 1; i>0; --i)
{
if( str[i] == '' )
{
str[i] = ' ';
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("/\"));
现在,在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;
}
重型和跨平台的方法将是使用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";
你可以使用下面的一行符来得到你想要的结果:
*(strrchr(str, '') + 1) = 0; // put extra NULL check before if path can have 0 '' also
在posix兼容的系统(*nix)上,有一个通用的dirname(3)
函数。在windows上有_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平台上,可以使用paththremovefilespec或PathCchRemoveFileSpec为了达到这个目的。但是,对于可移植性,我将采用这里建议的其他方法。
可以使用dirname获取父目录点击此链接获取更多信息
拉
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 具有默认值的引用获取函数
- xmake总是报告:错误:无法获取cxx的程序,为什么
- 在c++中获取大文件的大小