NeA*_*RAZ 16 c c++ windows winapi
Windows文件系统不区分大小写.如果给定一个文件/文件夹名称(例如"somefile"),我得到该文件/文件夹的实际名称(例如,如果Explorer显示它,它应该返回"SomeFile")?
我知道的一些方法,所有这些看起来都很倒退:
我错过了一些明显的WinAPI电话吗?最简单的一个,比如GetActualPathName()或GetFullPathName()使用传入的大小写返回名称(例如,如果传入,则返回"程序文件",即使它应该是"Program Files").
我正在寻找原生解决方案(不是.NET).
这是一个给定绝对路径,相对路径或网络路径的函数,它将返回大小写的路径,就像在Windows上显示的那样.如果路径的某个组件不存在,它将从该点返回传入的路径.
它非常复杂,因为它试图处理网络路径和其他边缘情况.它在宽字符串上运行,并使用std :: wstring.是的,理论上Unicode TCHAR可能与wchar_t不同; 这是读者的练习:)
std::wstring GetActualPathName( const wchar_t* path )
{
// This is quite involved, but the meat is SHGetFileInfo
const wchar_t kSeparator = L'\\';
// copy input string because we'll be temporary modifying it in place
size_t length = wcslen(path);
wchar_t buffer[MAX_PATH];
memcpy( buffer, path, (length+1) * sizeof(path[0]) );
size_t i = 0;
std::wstring result;
// for network paths (\\server\share\RestOfPath), getting the display
// name mangles it into unusable form (e.g. "\\server\share" turns
// into "share on server (server)"). So detect this case and just skip
// up to two path components
if( length >= 2 && buffer[0] == kSeparator && buffer[1] == kSeparator )
{
int skippedCount = 0;
i = 2; // start after '\\'
while( i < length && skippedCount < 2 )
{
if( buffer[i] == kSeparator )
++skippedCount;
++i;
}
result.append( buffer, i );
}
// for drive names, just add it uppercased
else if( length >= 2 && buffer[1] == L':' )
{
result += towupper(buffer[0]);
result += L':';
if( length >= 3 && buffer[2] == kSeparator )
{
result += kSeparator;
i = 3; // start after drive, colon and separator
}
else
{
i = 2; // start after drive and colon
}
}
size_t lastComponentStart = i;
bool addSeparator = false;
while( i < length )
{
// skip until path separator
while( i < length && buffer[i] != kSeparator )
++i;
if( addSeparator )
result += kSeparator;
// if we found path separator, get real filename of this
// last path name component
bool foundSeparator = (i < length);
buffer[i] = 0;
SHFILEINFOW info;
// nuke the path separator so that we get real name of current path component
info.szDisplayName[0] = 0;
if( SHGetFileInfoW( buffer, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) )
{
result += info.szDisplayName;
}
else
{
// most likely file does not exist.
// So just append original path name component.
result.append( buffer + lastComponentStart, i - lastComponentStart );
}
// restore path separator that we might have nuked before
if( foundSeparator )
buffer[i] = kSeparator;
++i;
lastComponentStart = i;
addSeparator = true;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
再次,感谢cspirz指向SHGetFileInfo.