From File Handle to FILE *pFILE

从 choosefile dlg 可以得到一个 OPENFILENAME, 进而可以创建一个 file handle, 但我想要的是一个 FILE * pFILE: 应该如何呢?

<Section 摘自http://blog.csdn.net/dijkstar/archive/2007/11/14/1884105.aspx>
_open_osfhandle()函数在windows下可以将一个win32打开的文件句柄映射成为一个普通的C库里面的流文件接口,参见下例:
  1. void OSFileToCRTFile()
  2.        {
  3.               HANDLE hFile = CreateFile("c://test.dat", GENERIC_READ | GENERIC_WRITE, 0, NULL,
  4.               OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  5.  
  6.               char szText[] = "Hello world!/n";
  7.               DWORD dwWritten;
  8.               WriteFile(hFile, szText, strlen(szText), &dwWritten, NULL);
  9.  
  10.               FILE* pFile = NULL;
  11.               int nHandle = _open_osfhandle((long)hFile, _O_TEXT | _O_APPEND);
  12.               if (nHandle != -1)
  13.               pFile = _fdopen(nHandle, "wt");
  14.  
  15.               if(pFile)
  16.               {
  17.                      int n = fputs("write by FILE*!", pFile);
  18.                      fflush(pFile);//立即写入文件
  19.                      // n == 0
  20.               }
  21.  
  22.               CloseHandle(hFile);
  23.        }
</Section>

这样,开启动话框并打开一个文件所需的代码:
  1. OPENFILENAME ofn;       // common dialog box structure
  2. char szFile[260] = {0};       // buffer for file name
  3. //HWND hwnd ;              // owner window
  4. HANDLE hf;              // file handle
  5. printf("initialising.../n");
  6. // Initialize OPENFILENAME
  7. ZeroMemory(&ofn, sizeof(ofn));
  8. ofn.lStructSize = sizeof(ofn);
  9. //ofn.hwndOwner = hwnd;
  10. ofn.lpstrFile = szFile;
  11. //
  12. // Set lpstrFile[0] to '/0' so that GetOpenFileName does not 
  13. // use the contents of szFile to initialize itself.
  14. //
  15. printf("setting.../n");
  16. ofn.lpstrFile[0] = '/0';
  17. ofn.nMaxFile = sizeof(szFile);
  18. ofn.lpstrFilter = "All/0*.*/0Text/0*.TXT/0";
  19. ofn.nFilterIndex = 1;
  20. ofn.lpstrFileTitle = NULL;
  21. ofn.nMaxFileTitle = 0;
  22. ofn.lpstrInitialDir = NULL;
  23. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
  24. printf("displaying.../n");
  25. // Display the Open dialog box. 
  26. if (GetOpenFileName(&ofn)==TRUE) {
  27.   hf = CreateFile(ofn.lpstrFile, GENERIC_READ,0, (LPSECURITY_ATTRIBUTES) NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,(HANDLE) NULL);
  28.   int nhandle = _open_osfhandle((long)hf, _O_RDONLY | _O_TEXT);
  29.   if (nhandle != -1){
  30.     FILE * pFile = _fdopen(nhandle, "r");
  31.     TestRead * pTest = new TestRead(pFile);
  32.     pTest->readVertices();
  33.     fclose(pFile);
  34.   }
  35.   CloseHandle(hf);
  36. }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值