一个C++按行读取Unicode 文本文件的例子

代码
#include "stdafx.h"
#include 
<windows.h>
#include 
<stdio.h>
#include 
<cwctype>
#include 
<string>
#include 
<iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    
if (argc == 2) {
        FILE 
*fp = NULL;
        errno_t err 
= _wfopen_s(&fp, argv[1], L"rb,ccs=Unicode");
        
if (err != 0) {
            cout 
<< "open file " << argv[1<< "failed. error code: " << err << endl;
        }

        wchar_t buf[
2048= {0}; // 假设每一行文本不超过2048字符
        size_t rdCount = fread(buf, 12, fp);
        
if (rdCount != 2) { fclose(fp); return 1; }

        
if (buf[0!= 0xFF || buf[1!= 0xFE) {
            fseek(fp, 
0, SEEK_SET); // 测试Unicode文件标志, 没有Unicode头,跳回文件头
        }

        
while (!feof(fp)) {
            
if (NULL != fgetws(buf, 2048, fp))
                wcout 
<< buf << endl;    
        }

        fclose(fp);
    }
    
return 0;
}

 

posted @ 2010-04-24 01:01  moonz-wu  阅读(2328)  评论(3编辑  收藏  举报