非Unicode工程读取Unicode文件

MyUnicodeReader.h

#pragma once
/************************************************************************/
/* 在“多字节字符集”属性的工程中读取Unicode文件
** -----------------------------------注意-------------------------------------------------------
** -------------一定要确保读取的文件是标准的Unicode文件,即文件头两个字节是0xFFFE---------*/
/************************************************************************/
class MyUnicodeReader
{
public:
    MyUnicodeReader(void);
    ~MyUnicodeReader(void);
    FILE* file;
    bool Open(CString filePath);
    void Close();
    //按行读取
    bool ReadString(CString &s);
};

MyUnicodeReader.cpp

#include "StdAfx.h"
#include "MyUnicodeReader.h"
#include <locale.h>
#include <string>


MyUnicodeReader::MyUnicodeReader(void)
{
}


MyUnicodeReader::~MyUnicodeReader(void)
{
}

bool MyUnicodeReader::Open( CString filePath )
{
    file=fopen(filePath, "rb");
    //Unicode文件开始前两个字节应该是FFFE
    fseek(file, 2, SEEK_SET);
    return file!=NULL;
}

void MyUnicodeReader::Close()
{
    fclose(file);
}

const int MAX_CHAR_NUM=1024;
bool MyUnicodeReader::ReadString( CString &s )
{
    wchar_t buf[MAX_CHAR_NUM];
    if (fgetws(buf, MAX_CHAR_NUM, file)==NULL) return false;
    size_t convertedChars = 0;
    char dst[MAX_CHAR_NUM];
    setlocale(LC_CTYPE,"chs");// 处理汉字
    wcstombs_s(&convertedChars, dst, MAX_CHAR_NUM, buf, MAX_CHAR_NUM);
    s=dst;
    return true;
}
原文地址:https://www.cnblogs.com/coolbear/p/4758127.html