根据文件句柄,获取文件名

#include <windows.h> #include <stdio.h> #include <tchar.h> #include <string.h> #include <psapi.h> #define BUFSIZE 512 BOOL GetFileNameFromHandle(HANDLE hFile) {   BOOL bSuccess = FALSE;   TCHAR pszFilename[MAX_PATH+1];   HANDLE hFileMap;   // Get the file size.   DWORD dwFileSizeHi = 0;   DWORD dwFileSizeLo = GetFileSize(hFile, &dwFileSizeHi);   if( dwFileSizeLo == 0 && dwFileSizeHi == 0 )   {      printf("Cannot map a file with a length of zero./n");      return FALSE;   }   // Create a file mapping object.   hFileMap = CreateFileMapping(hFile,                     NULL,                     PAGE_READONLY,                     0,                     1,                     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))       {         // Translate path with device name to drive letters.         TCHAR szTemp[BUFSIZE];         szTemp[0] = '/0';         if (GetLogicalDriveStrings(BUFSIZE-1, szTemp))         {           TCHAR szName[MAX_PATH];           TCHAR szDrive[3] = TEXT(" :");           BOOL bFound = FALSE;           TCHAR* p = szTemp;           do           {             // Copy the drive letter to the template string             *szDrive = *p;             // Look up each device name             if (QueryDosDevice(szDrive, szName, BUFSIZE))             {               UINT uNameLen = _tcslen(szName);               if (uNameLen < MAX_PATH)               {                 bFound = _tcsnicmp(pszFilename, szName,                     uNameLen) == 0;                 if (bFound)                 {                   // Reconstruct pszFilename using szTemp                   // Replace device path with DOS path                   TCHAR szTempFile[MAX_PATH];                   _stprintf(szTempFile,                             TEXT("%s%s"),                             szDrive,                             pszFilename+uNameLen);                   _tcsncpy(pszFilename, szTempFile, MAX_PATH);                 }               }             }             // Go to the next NULL character.             while (*p++);           } while (!bFound && *p); // end of string         }       }       bSuccess = TRUE;       UnmapViewOfFile(pMem);     }     CloseHandle(hFileMap);   }   printf("File name is %s/n", pszFilename);   return(bSuccess); }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值