1. 程式人生 > >[C/C++標準庫]_[初級]_[讀寫中文路徑的檔案--寫入unicode字串]

[C/C++標準庫]_[初級]_[讀寫中文路徑的檔案--寫入unicode字串]

場景:

1. 需要寫入非ascii文字並且與本地編碼無關時,除了utf8,unicode編碼是另外一個選擇,它的好處是佔兩個位元組,便於統計字元和對字元進行處理,因為有對應的寬位元組的函式,如wcslen.

2.使用_wfopen支援中文路徑.

程式碼1,寫入二進位制值:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    const wchar_t* str = L"a中國人的國家asdfamn12312";
    FILE* file = _wfopen(L"E:\\中文.txt",L"w");
    char header[]={0xff,0xfe};
    fwrite(header,1,sizeof(header),file);
    printf("%d\n",wcslen(str)*2);
    fwrite(str,1,wcslen(str)*2,file);
    //fwprintf(file,L"%S",str);以ANSI模式開啟檔案,這個函式時用不了的.
    fclose(file);
    return 0;
}

fwprintf is a wide-character version offprintf; infwprintf,format is a wide-character string. These functions behave identically if the stream is opened in ANSI mode.fprintf does not currently support output into a UNICODE stream.

如果要使用fwprintf的話,要以unicode模式開啟檔案.

程式碼2,寫入unicode字串:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define _UNICODE

int main(int argc, char const *argv[])
{
	const wchar_t* str = L"a中國人的國家asdfamn12312";
	FILE* file = _wfopen(L"E:\\中文.txt",L"w, ccs=UNICODE");
	char header[]={0xff,0xfe};
	//fwrite(header,1,sizeof(header),file);
	printf("%d\n",wcslen(str)*2);
	//fwrite(str,1,wcslen(str)*2,file);
	fwprintf(file,L"%s",str);
	fclose(file);
	return 0;
}