我偶然发现了 GetFullPathName()
的行为(通过使用 QFileInfo::canonicalFilePath()
)我不太明白:当我用一个由当前驱动器号和一个冒号组成的字符串调用这个函数时,它返回当前工作目录的路径,而我希望驱动器号的路径。
下面的代码举例说明了我在说什么:
#include <windows.h>
#include <iostream>
#include <string>
std::string canonicalFilePath(const char *path)
{
static const std::size_t BufferSize = 300;
char canonicalPath[BufferSize];
GetFullPathName(path, BufferSize, canonicalPath, 0);
return std::string(canonicalPath);
}
int main(int, char **)
{
SetCurrentDirectory("C:/some/path");
std::cout << "In C:" << '\n';
std::cout << " C -> " << canonicalFilePath("C") << '\n'
<< " C: -> " << canonicalFilePath("C:") << '\n'
<< " C:/ -> " << canonicalFilePath("C:/") << '\n'
<< " D -> " << canonicalFilePath("D") << '\n'
<< " D: -> " << canonicalFilePath("D:") << '\n'
<< " D:/ -> " << canonicalFilePath("D:/") << '\n';
SetCurrentDirectory("D:/other/path");
std::cout << "In D:" << '\n';
std::cout << " C -> " << canonicalFilePath("C") << '\n'
<< " C: -> " << canonicalFilePath("C:") << '\n'
<< " C:/ -> " << canonicalFilePath("C:/") << '\n'
<< " D -> " << canonicalFilePath("D") << '\n'
<< " D: -> " << canonicalFilePath("D:") << '\n'
<< " D:/ -> " << canonicalFilePath("D:/") << '\n';
}
输出:
In C:
C -> C:\some\path\C // ok
C: -> C:\some\path // ? why not C:\ ?
C:/ -> C:\ // ok
D -> C:\some\path\D // ok
D: -> D:\ // ok
D:/ -> D:\ // ok
In D:
C -> D:\other\path\C // ok
C: -> C:\ // ok
C:/ -> C:\ // ok
D -> D:\other\path\D // ok
D: -> D:\other\path // ? why not D:\ ?
D:/ -> D:\ // ok
这种行为正常吗?在 GetFullPathName
documentation , 据称
If you specify "U:" the path returned is "U:\"
如果“U”是当前驱动器盘符,为什么不是这种情况?
最佳答案
来自 msdn :
If a file name begins with only a disk designator but not the backslash after the colon, it is interpreted as a relative path to the current directory on the drive with the specified letter. Note that the current directory may or may not be the root directory depending on what it was set to during the most recent "change directory" operation on that disk.
Examples of this format are as follows:
- "C:tmp.txt" refers to a file named "tmp.txt" in the current directory on drive C.
- "C:tempdir\tmp.txt" refers to a file in a subdirectory to the current directory on drive C.
关于c++ - 为什么 GetFullPathName 返回工作目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19677387/