如何將Unicode文字寫到日誌檔案中

2021-06-20 02:16:22 字數 1865 閱讀 2556

有時為了定位問題,我們需要結合列印日誌來處理。特別是較難復現的,一般都需要檢視上下文日誌才能找出可能存在的問題。考慮到程式要在不同語言的作業系統上執行,程式介面顯示要支援unicode,列印出來的日誌也要支援unicode,即將執行日誌以unicode文字寫到日誌檔案中。

那麼如何才能將unicode文字寫到日誌檔案中呢?只要我們呼叫unicode版本的寫入函式,傳入unicode字串就能實現寫入了嗎?試一試便知道,僅僅這樣肯定實現不了的。經實際除錯和使用,只要滿足下面幾點即可:

1、檔案以二進位制方式開啟;

2、寫入unicode文字標識頭:0xfffe;

3、呼叫unicode版本的寫入函式,傳入unicode字串;

4、如果列印日誌中要換行,僅僅\n是不行的,要用\r\n。

1、c函式寫日誌示例**:

void writelog( lpctstr pszlog, lpctstr pszfilepath )

bool bfileexsit = pathfileexists( pszfilepath );

lpctstr pszmode = null;

#ifdef _unicode

pszmode = _t("ab+"); // 對於unicode,要向檔案中寫入unicode文字,必須以二進位制方式開啟

#else

pszmode = _t("a+");

#endif

file* pfile;

pfile = _tfopen( pszfilepath , pszmode );

if( null == pfile )

if ( !bfileexsit )

; // unicode頭

fwrite( chunicodehead, sizeof(byte), sizeof(chunicodehead), pfile );

} systemtime time;

::getlocaltime( &time );

_ftprintf( pfile, _t("%04d-%02d-%02d %02d:%02d:%02d %s\r\n"), time.wyear, time.wmonth, time.wday, time.whour, time.wminute, time.wsecond, pszlog );

fclose( pfile );

return;

}

2、mfc中的cstdiofile示例:

void writelog( lpctstr pszlog, lpctstr pszfilepath )

cstdiofile logfile;

cfileexception ex;

bool bfileexsit = pathfileexists( pszfilepath );

uint uopenflag = cfile::sharedenynone | cfile::modecreate | cfile::modewrite | cfile::modenotruncate;

#ifdef _unicode

uopenflag |= cfile::typebinary; // 對於unicode版本,要寫入unicode文字,所以要設定cfile::typebinary標記

#endif

bool32 bret = logfile.open( pszfilepath, uopenflag, &ex );

if ( bret )

#endif

flog.seektoend();

flog.writestring( achprintbuf );

flog.close();

}}

如何將Unicode文字寫到日誌檔案中

有時為了定位問題,我們需要結合列印日誌來處理。特別是較難復現的,一般都需要檢視上下文日誌才能找出可能存在的問題。考慮到程式要在不同語言的作業系統上執行,程式介面顯示要支援unicode,列印出來的日誌也要支援unicode,即將執行日誌以unicode文字寫到日誌檔案中。那麼如何才能將unicode...

利用Python如何將資料寫到CSV檔案中

我們從網上爬取資料,最後一步會考慮如何儲存資料。如果資料量不大,往往不會選擇儲存到資料庫,而是選擇儲存到檔案中,例如文字檔案 csv 檔案 xls 檔案等。因為檔案具備攜帶方便 查閱直觀。python 作為膠水語言,搞定這些當然不在話下。但在寫資料過程中,經常因資料來源中帶有中文漢字而報錯。最讓人頭...

如何將中文轉換為Unicode字符集

size large 在一些程式設計過成功會遇到一些中文問題,當然解決的方法很多。這裡我提供一種如何將中文轉換成unicode字符集的方法 利用jdk1.6找到bin目錄下的檔案native2ascii.exe。1在cmd中進入到native2ascii.exe的路徑下 直接敲native2asci...