Hôm nay Dũng Còi hỏi một câu:
- Làm thế nào để mở một file mà tên của nó ở dạng Unicode hả anh? Ví dụ: Dũng_Còi.txt
- Trả lời:
Trường hợp này không thể sử dụng kiểu char 8-bit thông thường, vì là có kèm kí tự Unicode mở rộng nên ta cần sử dụng tới kiểu kí tự mở rộng wchar_t (16 bit Unicode)
Với khai báo kiểu wchar_t thì các chuỗi thông thường phải xác định bởi chữ L ở trước.
Ví dụ:
Mã:
wchar_t* filename = L"Dũng_Còi.txt";
Nếu bạn viết là:
Mã:
wchar_t* filename = "Dũng_Còi.txt";
lập tức sẽ bị lỗi vì phép gán không tương xứng, không thể ép kiểu từ 8-bit char lên 16-bit wchar_t.
Code sau đây demo cách đọc tên file dạng Unicode như nói ở trên:
Mã:
/* * @author Xcross87 * @date 03-May-2009 * @file openfile.cpp * @note * open file name which is Unicode */ /* prototype */#include <stdio.h> /* declare: function */int OpenFile(wchar_t*, wchar_t*);int OpenFileEx(wchar_t*, wchar_t*); /* entry point */int main(void){ // file name in unicode wchar_t* fname = L"DũngCòi.txt"; // open if(OpenFileEx(fname, L"r")) printf("OK
"); else printf("Error
"); // return return 0;} // @function OpenFile()// @type int// @param // wchar_t* _iFileName file name in 16-bit Unicode// wchar_t* _mode file mode// @return // 0 if fail// 1 if successint OpenFile(wchar_t *_iFileName, wchar_t *_mode){ FILE* __stream; __stream = _wfopen(_iFileName,_mode); if(NULL == __stream) { return 0; } fclose(__stream); return 1;} // @function OpenFileEx()// @type int// @param // wchar_t* _iFileName file name in 16-bit Unicode// wchar_t* _mode file mode// @return // 0 if fail// 1 if successint OpenFileEx(wchar_t* _iFileName, wchar_t* _mode){ FILE* __stream; int errno = _wfopen_s(&__stream, _iFileName, _mode); if(0 != errno) return 0; fclose(__stream); return 1;}
Chúc vui vẻ! ^^~!
View more random threads:
Thông qua phân tích dữ liệu Google từ 86 quốc gia, mới đây, một công ty tại Anh đã công bố bảng xếp hạng kích tấc "cậu nhỏ" của các nước trên thế giới. Kết quả, hầu hết các nước xếp ở nhóm đầu của...
"Chim" của chàng trai Việt thuộc...