[an error occurred while processing this directive]
|
Obtaining a File Name From a File Handle
The following example obtains a file name from a file handle by creating a file mapping object. It prints the fully qualified path of the file name, including the drive letter.
When using this sample code, be sure to add standard error checking for all functions.
BOOL GetFilenameFromHandle(HANDLE hFile)
{
BOOL bSuccess = FALSE;
TCHAR* pszFilename[MAX_PATH+1];
uint uMaxLenDest = 0;
// Get the file size.
DWORD dwFileSizeHi = 0;
DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);
// Create a file mapping object.
HANDLE hFileMap = CreateFileMapping(hFile,
NULL,
PAGE_READONLY,
0,
dwFileSizeLo,
NULL);
if (hFileMap) {
// Create a file mapping to get the file name.
void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
if (pMem) {
if (GetMappedFileName (GetCurrentProcess(),
pMem,
pszFilename,
MAX_PATH)) {
// Attempt to translate the path with device name into drive
// letters.
TCHAR szTemp[512];
*szTemp = NULL;
if (GetLogicalDriveStrings(MAX_ARRAY_ITEMS(szTemp)-1,
szTemp)) {
TCHAR szName[MAX_PATH];
TCHAR szDrive[3] = TEXT(" :");
BOOL bFound = FALSE;
TCHAR* p = szTemp;
do {
// Copy the drive letter into the template string,
// removing the backslash.
*szDrive = *p;
// Look up each device name.
if (QueryDosDevice(szDrive, szName,
MAX_ARRAY_ITEMS(szName))) {
uint uNameLen = _tcslen(szName);
// If greater than file name length, it's not a match.
if (uNameLen < uMaxLenDest) {
bFound = _tcsnicmp(pszFilename, szName, uNameLen)
== 0;
if (bFound) {
// Reconstruct pszFilename using szTemp as scratch,
// and replace device path with our DOS path.
TCHAR szTempFile[MAX_PATH];
_stprintf(szTempFile,
TEXT("%s%s"),
szDrive,
pszFilename+uNameLen);
stringCopy(pszFilename, szTempFile, uMaxLenDest);
}
}
}
// Go to the next NULL character.
while (*p++);
} while (!bFound && *p); // at the end of the string
}
}
bSuccess = TRUE;
if (!UnmapViewOfFile(pMem)) assert(0);
}
if (!CloseHandle(hFileMap)) assert(0);
}
return(bSuccess);
}
E-mail: info@telesys.ru