C++ 在文件扩展名之前查找文件名

C++ Find file name before file extension

我是 C++ 的新手,学习曲线已经教会了我很多东西,但现在我真的需要找到一种快速、巧妙的方法。

我尝试了很多方法,但无法弄清楚(或者它有效;但部分有效)。

size_t found = strFullPathName.find(".file001");

if (found != string::npos)
{
    //Find us the filename, and return in correct format.
    strFullPathName = strFullPathName.substr(0, strFullPathName.find(".file001"));
    strFullPathName = szCurDir + "\output\" + strFullPathName + ".file001";
}

上面的代码,在 .file001 扩展名之前给了我 anything

但实际上我想要的只是一种获取文件名的方法。

这可以有或没有扩展名,最好没有。

这可以通过多种方式完成,我敢肯定。但我似乎无法找到一种简单快捷的方法。

预先感谢您帮助我。

如果你有 C++17,使用这个:

std::filesystem::path(strFullPathName).stem()

这将为您提供不带扩展名的文件名,并且适用于支持 C++17 的任何平台。参见 https://en.cppreference.com/w/cpp/filesystem/path/stem

如果您没有 C++17,但使用的是 POSIX-style 系统,例如 Linux 或 Mac OS,basename() 会给您包含扩展名的文件名。

如果您没有 C++17 并且正在使用 Windows,请尝试 _splitpath_s()

要仅提取文件名,只需 rfind()find_last_of() 字符串中的最后一个 '/' and/or '\' 字符,具体取决于平台,然后 substr() 之后的所有内容。

然后,要删除扩展名,您可以 rfind() 提取文件名中的最后 '.' 个字符,然后 substr() 它之前的所有内容。

size_t found = strFullPathName.find_last_of("/\");
if (found != string::npos)
{
    //Find us the filename, and return in correct format.
    strFullPathName = strFullPathName.substr(found+1);
    found = strFullPathName.rfind(".");
    if (found != string::npos)
        strFullPathName = strFullPathName.substr(0, found);
    strFullPathName = szCurDir + "\output\" + strFullPathName + ".file001";
}