C++17标准filesystem和windows微软原生api获取文件绝对路径的方法

xiaoxiao2021-02-28  26

filesystem一开始集成于c++的boost库,在C++17标准中,终于集成了filesytem。

这里,我来使用微软的VS2017 15.7.0 Preview 5.0来测试这个功能。

首先我们来引用这两个头文件

#include <experimental/filesystem> // C++-standard header file name #include <filesystem> // Microsoft-specific implementation header file name

然后引用std和experimental::filesystem这两个命名空间。

using namespace std; using namespace std::experimental::filesystem;声明一个wstring类型的字符串变量做为路径 wstring DriverPath = TEXT(".\\Driver.sys");

将路径赋值给filesystem(文件系统)的path类型

path path = DriverPath;

然后我们通过filesystem的canonical函数来获取绝对路径

//c++17 cout << "c++ 17 get path: " << canonical(path) << endl;

使用windows原生api:调用win32的GetFullPathName函数

#define BUFSIZE 4096 wstring DriverPath = TEXT(".\\Driver.sys"); int main() { path path = DriverPath; DWORD retval = 0; TCHAR buffer[BUFSIZE] = TEXT(""); TCHAR buf[BUFSIZE] = TEXT(""); TCHAR** lppPart = { NULL }; //windows api retval = GetFullPathName(DriverPath.c_str(), BUFSIZE, buffer, lppPart); if (retval != 0) _tprintf(TEXT("win api get path: %s\n"), buffer); }

附录:

c++文件系统文档:http://zh.cppreference.com/w/cpp/filesystem

微软文件系统文档:https://docs.microsoft.com/en-us/cpp/standard-library/filesystem

boost库文件系统文档:https://www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#canonical

微软GetFullPathName函数文档:https://msdn.microsoft.com/en-us/library/windows/desktop/aa364963(v=vs.85).aspx

完整代码:

#include <iostream> #include <string> #include <experimental/filesystem> // C++-standard header file name #include <filesystem> // Microsoft-specific implementation header file name using namespace std; using namespace std::experimental::filesystem; #define BUFSIZE 4096 wstring DriverPath = TEXT(".\\Driver.sys"); int main() { path path = DriverPath; DWORD retval = 0; TCHAR buffer[BUFSIZE] = TEXT(""); TCHAR buf[BUFSIZE] = TEXT(""); TCHAR** lppPart = { NULL }; //windows api retval = GetFullPathName(DriverPath.c_str(), BUFSIZE, buffer, lppPart); if (retval != 0) _tprintf(TEXT("win api get path: %s\n"), buffer); //c++17 cout << "c++ 17 get path: " << canonical(path) << endl; }

转载请注明原文地址: https://www.6miu.com/read-2629636.html

最新回复(0)