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

问题描述 投票:0回答:7

我需要从 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。

c++ visual-c++ dev-c++
7个回答
20
投票

如果您使用 std::string 而不是 C 风格的字符数组,则可以按以下方式使用 string::find_last_ofstring::substr

std::string str = "D:\\Devs\\Test\\sprite.png";
str = str.substr(0, str.find_last_of("/\\"));

14
投票

现在,在 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;
    }

4
投票

重型和跨平台方法是使用boost::filesystem::parent_path()。但显然这会增加您可能不希望的开销。

或者,您可以使用 cstring 的 strrchr 函数,如下所示:

include <cstring>
char * lastSlash = strrchr( str, '\\');
if ( *lastSlash != '\n') *(lastSlash +1) = '\n';

3
投票

编辑 const 字符串是未定义的行为,因此声明如下:

char str[] = "D:\\Devs\\Test\\sprite.png";

您可以使用以下 1 种内衬来获得您想要的结果:

*(strrchr(str, '\\') + 1) = 0; // put extra NULL check before if path can have 0 '\' also

3
投票

在 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;
}

2
投票

在Windows平台上,您可以使用 PathRemoveFileSpecPathCchRemoveFileSpec 为了达成这个。 但是,为了可移植性,我会采用此处建议的其他方法。


-3
投票

您可以使用 dirname 来获取父目录 检查此链接了解更多信息

拉古

© www.soinside.com 2019 - 2024. All rights reserved.