none
请问ReadFile把Unicode的TXT文本,读出来放到char *,是乱码啊 RRS feed

  • 问题

  •         第一种读法,放到char*,是乱码,转为宽字节后还是乱码
     HANDLE hSrcFile = CreateFile(_T("F:\\011-002.txt"), GENERIC_READ, 0, NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    DWORD dwNumOfBytesRead=233;
    char* cBuffer=new char[sizeof(char)*1024];
    ReadFile(hSrcFile, cBuffer, 1024*2, &dwNumOfBytesRead, NULL);//读取内容,但是乱码来的
    byte c1=tBuffer[0];
    byte c2=tBuffer[1];
    byte c3=tBuffer[2];
    byte c4=tBuffer[3];   //字节是对的 
            int   nLen=strlen(cBuffer)+1;  
    int   nwLen=MultiByteToWideChar(CP_ACP,0,cBuffer,nLen,NULL,0);  
    TCHAR *tBuffer = (TCHAR*)malloc(sizeof(TCHAR)*nwLen);
    memset(tBuffer,0,sizeof(TCHAR)*nwLen);
    int iReturn=MultiByteToWideChar(CP_ACP,0,cBuffer,nLen,tBuffer,nwLen);   //转为宽字节后,还是乱码
    第二种:读出来放到TCHAR*里,读出来的内容正确,但字节得不到了(问题)
    HANDLE hSrcFile = CreateFile(_T("F:\\011-002.txt"), GENERIC_READ, 0, NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    DWORD dwNumOfBytesRead;
    TCHAR *tBuffer = (TCHAR*)malloc(sizeof(TCHAR)*1024);
    memset(tBuffer,0,sizeof(TCHAR)*1024);
        ReadFile(hSrcFile, tBuffer, 1024*2, &dwNumOfBytesRead, NULL);//读取内容,正确
    byte b1= tBuffer[0];
    byte b2=tBuffer[1];
    byte b3= tBuffer[2];
    byte b4=tBuffer[3];   //这样读字节应该不对的,所以我用以下转为char×来取字节
    int size=WideCharToMultiByte(CP_ACP,0,tBuffer,-1,NULL,0,NULL,NULL);
    char *cBuffer=new char[size+1];
        int iReturn=WideCharToMultiByte(CP_ACP,0,tBuffer,-1,cBuffer,size,NULL,NULL);//转为char *  ,内容前面出现了 ?
        int a=GetLastError();
    byte c1= cBuffer[0];
    byte c2=cBuffer[1];
    byte c3= cBuffer[2];
    byte c4=cBuffer[3];  //字节不对
    请问,怎么即得到内容,又得到字节啊???高手分析一下,我上面这两种做法,哪里出问题了???
            
    2011年5月3日 4:31

答案

  • 11.txt编码为Unicode

    ---------------------------------------------------------------------------
    HANDLE hFile = CreateFile(_T("F:\\11.txt"), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
      if(INVALID_HANDLE_VALUE != hFile)
      {
       DWORD dwSize = GetFileSize(hFile, NULL);
       wchar_t* szText = new wchar_t[dwSize+1];
       memset(szText, 0, sizeof(wchar_t) * (dwSize+1));
       DWORD dwRead = 0;
       if(INVALID_SET_FILE_POINTER != SetFilePointer(hFile, 2, NULL, FILE_BEGIN))
       {
        if(ReadFile(hFile, szText, dwSize, &dwRead, NULL))
        {
         char* buf = NULL;
         int len = WideCharToMultiByte(CP_ACP, 0, szText, -1, buf, 0, NULL, NULL);
         buf = new char[len];
         memset(buf, 0, len);
         WideCharToMultiByte(CP_ACP, 0, szText, -1, buf, len, NULL, NULL);
         
         printf("%s\r\n", buf);

         delete[] buf;
         buf = NULL;
        }
       }
       delete[] szText;
       szText = NULL;

       CloseHandle(hFile);
      }


    Visual C++ enthusiast, like network programming and driver development. At present is being engaged in the WinCE/Windows Mobile platform embedded development.
    2011年5月3日 6:56
    版主