今天从CSDN看见有人问如何从 http://community.csdn.net/Expert/TopicView1.asp?id=5164878 提问从打开的文件句柄获得文件的路径,下面是解决的办法:
#include
<
Psapi.h
>
#define BUFSIZE
512
#pragma comment(lib,
"
Psapi.lib
"
)
BOOL __stdcall GetFileNameFromHandle(HANDLE hFile, LPWSTR lpFileName, DWORD dwSize)
{
BOOL bSuccess
=
FALSE;
WCHAR pszFilename[MAX_PATH
+
1
];
HANDLE hFileMap;
DWORD dwFileSizeHi
=
0
;
DWORD dwFileSizeLo
=
::GetFileSize(hFile,
&
dwFileSizeHi);
if
( dwFileSizeLo
==
0
&&
dwFileSizeHi
==
0
)
{
return
bSuccess;
}
hFileMap
=
::CreateFileMappingW(hFile,
NULL,
PAGE_READONLY,
0
,
1
,
NULL);
if
(hFileMap)
{
void
*
pMem
=
::MapViewOfFile(hFileMap, FILE_MAP_READ,
0
,
0
,
1
);
if
(pMem)
{
if
(::GetMappedFileNameW(GetCurrentProcess(),
pMem,
pszFilename,
MAX_PATH))
{
WCHAR szTemp[BUFSIZE];
szTemp[
0
]
=
L'\
0
';
if
(::GetLogicalDriveStringsW(BUFSIZE
-
1
, szTemp))
{
WCHAR szName[MAX_PATH];
WCHAR szDrive[
3
]
=
L
"
:
"
;
BOOL bFound
=
FALSE;
WCHAR
*
p
=
szTemp;
do
{
*
szDrive
=
*
p;
if
(::QueryDosDeviceW(szDrive, szName, BUFSIZE))
{
UINT uNameLen
=
lstrlenW(szName);
if
(uNameLen
<
MAX_PATH)
{
bFound
=
::_wcsnicmp(pszFilename, szName,
uNameLen)
==
0
;
if
(bFound)
{
WCHAR szTempFile[MAX_PATH];
::wsprintfW(szTempFile,
L
"
%s%s
"
,
szDrive,
pszFilename
+
uNameLen);
::lstrcpynW(pszFilename, szTempFile, MAX_PATH);
}
}
}
while
(
*
p
++
);
}
while
(
!
bFound
&&
*
p);
}
}
::UnmapViewOfFile(pMem);
}
::CloseHandle(hFileMap);
}
if
(lpFileName)
{
::lstrcpynW(lpFileName,pszFilename,dwSize);
bSuccess
=
TRUE;
}
return
(bSuccess);
}