GbkToUtf8 Utf8ToGbk PackHttp

void CFunc::GbkToUtf8(CString &strGBK)
{
    int len = MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, NULL, 0);
    unsigned short *wszUtf8 = new unsigned short[len + 1];
    memset(wszUtf8, 0, len * 2 + 2);
    MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, wszUtf8, len);
    len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
    char *pszUtf8 = new char[len + 1];
    memset(pszUtf8, 0, len + 1);
    WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, pszUtf8, len, NULL, NULL);
    strGBK = (CString)pszUtf8;

    delete []pszUtf8;
    delete []wszUtf8;
    return;
}

void CFunc::Utf8ToGbk(CString &strUtf8)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, NULL, 0);
    unsigned short *wszGBK = new unsigned short[len + 1];
    memset(wszGBK, 0, len * 2 + 2);
    MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, wszGBK, len);
    len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
    char *pszGBK = new char[len + 1];
    memset(pszGBK, 0, len + 1);
    WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, pszGBK, len, NULL, NULL);
    strUtf8 = (CString)pszGBK;

    delete []pszGBK;
    delete []wszGBK;
    return;
}

long CFunc::PackHttp(const char *URL, const char *fileName)
{
    FILE *fp = NULL;
    char *buffer = new char[MAXBUF];
    ULONG nBytesRead = 0;
    CString strRead = "";
    ULONG lTotal = 0;

    CInternetSession session(NULL, 1, INTERNET_OPEN_TYPE_DIRECT, NULL, 0);
    CStdioFile *pFile = NULL;

    memset(buffer, 0, sizeof(buffer));
    fp = fopen(fileName, "wb");

    try
    {
        pFile = session.OpenURL(URL, 0, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);
        if (!pFile)
        {
            fclose(fp);
            ::DeleteFile(fileName);
            delete []buffer;
            return  -1;
        }
        nBytesRead = pFile->Read(buffer, MAXBUF - 10);
        while (nBytesRead > 0)
        {
            lTotal += nBytesRead;
            fwrite(buffer, 1, nBytesRead, fp);
            memset(buffer, 0, sizeof(buffer));
            nBytesRead = pFile->Read(buffer, MAXBUF - 10);
        }
    }
    catch (CInternetException *e)
    {
        fclose(fp);
        ::DeleteFile(fileName);
        e->Delete();
        return  - 2;
    }
    fclose(fp);
    return lTotal;
}
原文地址:https://www.cnblogs.com/klxll/p/3239997.html