Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在vc+;中,仅从文件的完整路径中查找文件名+;_C++_File_Visual C++ - Fatal编程技术网

C++ 在vc+;中,仅从文件的完整路径中查找文件名+;

C++ 在vc+;中,仅从文件的完整路径中查找文件名+;,c++,file,visual-c++,C++,File,Visual C++,假设有一个CString变量存储文件的完整路径。现在我只能从if中找到文件名。如何在vc++中实现 CString FileName = "c:\Users\Acer\Desktop\FolderName\abc.dll"; 现在我只想要你可以使用的abc.dll 请记住,您必须转义路径字符串中的\字符 std::string str = "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll"; std::string res = str.substr(

假设有一个CString变量存储文件的完整路径。现在我只能从if中找到文件名。如何在vc++中实现

CString FileName = "c:\Users\Acer\Desktop\FolderName\abc.dll";
现在我只想要你可以使用的abc.dll

请记住,您必须转义路径字符串中的
\
字符

std::string str = "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll";
std::string res = str.substr( str.find_last_of("\\") + 1 );
将为您提供“abs.dll”。

我将用于文件名操作,因为它了解名称的各个部分。这里需要的函数是filename()


如果您只是获取文件名,那么可以使用CString函数来实现。首先使用ReverseFind找到ast反斜杠,然后向右找到所需的字符串

下面的代码演示如何从完整路径提取文件名

#include <iostream>
#include <cstdlib>
#include <string>
#include <algorithm>

std::string get_file_name_from_full_path(const std::string& file_path)
{
    std::string file_name;

    std::string::const_reverse_iterator it = std::find(file_path.rbegin(), file_path.rend(), '\\');
    if (it != file_path.rend())
    {
        file_name.assign(file_path.rbegin(), it);
        std::reverse(file_name.begin(), file_name.end());
        return file_name;
    }
    else
        return file_name;
}

int main()
{
    std::string file_path = "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll";
    std::cout << get_file_name_from_full_path(file_path) << std::endl;
    return EXIT_SUCCESS;
}
#包括
#包括
#包括
#包括
std::string从完整路径获取文件名(const std::string和文件路径)
{
std::字符串文件名;
std::string::const\u reverse\u iterator it=std::find(file\u path.rbegin(),file\u path.rend(),“\\”);
if(it!=file_path.rend())
{
file_name.assign(file_path.rbegin(),it);
std::reverse(文件名.begin(),文件名.end());
返回文件名;
}
其他的
返回文件名;
}
int main()
{
std::string file_path=“c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll”;

std::cout与前面所述的相同,但由于您使用的是MFC框架,这将是实现此目的的方法。尽管这不会检查文件是否存在

CString path= "c:\\Users\\Acer\\Desktop\\FolderName\\abc.dll";
CString fileName= path.Mid(path.ReverseFind('\\')+1);

为什么要使用std::string当您有具有所需函数的CString时,您必须避开反斜杠。我建议使用所述的函数decomposePath。顺便说一句,CString不仅仅用于MFC-请参阅@Mark,为什么要转换?如果它是char*-ANSI build,请传递char*!