2014-03-01 82 views
2

我寫了一個程序,我在一個結構中存儲文件名列表,我必須將它打印在一個文件中。文件名的類型在LPCWSTR中,並且只用文件名地址打印如果使用ofstream類。我也嘗試過使用wofstream,但它導致「在閱讀位置訪問衝突」。我搜索網站以緩解此問題,但無法獲得適當的解決方案。許多建議嘗試使用wctombs函數,但我無法理解將LPCWSTR打印到文件是如何有用的。請幫助我緩解這種情況。打印LPCWSTR字符串到文件

我的代碼是這樣的,

ofstream out; 
out.open("List.txt",ios::out | ios::app); 
    for(int i=0;i<disks[data]->filesSize;i++) 
        { 
         //printf("\n%ws",disks[data]->lFiles[i].FileName); 
         //wstring ws = disks[data]->fFiles[i].FileName; 
         out <<disks[data]->fFiles[i].FileName << "\n"; 
        } 
        out.close(); 
+0

我不應該['std :: owfstream'](http://en.cppreference.com/w/cpp/io/bas ic_ofstream),標準輸出文件流的'wchar_t'版本並實現爲'basic_ofstream ',會給你帶來你想要的嗎?從技術上講,「正確的」是轉換,但它可能已經足夠。 – WhozCraig

+0

@ WhozCraig ..請告訴我如何轉換或類型轉換或其他? – WarriorPrince

+0

[將C++ LPCWSTR打印到文件]的可能重複(http://stackoverflow.com/questions/716653/printing-a-c-lpcwstr-to-a-file) –

回答

3

如果你想轉換,然後這應該工作(我無法得到wcstombs工作):

#include <fstream> 
#include <string> 
#include <windows.h> 

int main() 
{ 
    std::fstream File("File.txt", std::ios::out); 

    if (File.is_open()) 
    { 
     std::wstring str = L"русский консоли"; 

     std::string result = std::string(); 
     result.resize(WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, 0, 0)); 
     char* ptr = &result[0]; 
     WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, ptr, result.size(), 0, 0); 
     File << result; 
    } 
} 

使用原始字符串(因爲評論抱怨我使用std::wstring):

#include <fstream> 
#include <windows.h> 

int main() 
{ 
    std::fstream File("File.txt", std::ios::out); 

    if (File.is_open()) 
    { 
     LPCWSTR wstr = L"русский консоли"; 
     LPCSTR result = NULL; 

     int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, 0, 0); 

     if (len > 0) 
     { 
      result = new char[len + 1]; 
      if (result) 
      { 
       int resLen = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &result[0], len, 0, 0); 

       if (resLen == len) 
       { 
        File.write(result, len); 
       } 

       delete[] result; 
      } 
     } 
    } 
}