从c++文件中获取父目录

visual Get parent directory from file in C++

本文关键字:获取 c++ 文件      更新时间:2023-10-16

我需要从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获取父目录点击此链接获取更多信息