CLogFile写日志

CLogFile::CLogFile()
{

}

CLogFile::~CLogFile()
{

}
//获取文件名称
CString CLogFile::GetFileName()
{
    CString m_sFileName;

    m_sFileName = CTime::GetCurrentTime().Format("%Y-%m-%d") + _T(".log");

    return m_sFileName;
}
//获取应用程序所在路径
CString CLogFile::GetFilePath()
{   
    CString m_FilePath;

    GetModuleFileName(NULL,m_FilePath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);

    m_FilePath.ReleaseBuffer();

    int m_iPosIndex;

    m_iPosIndex = m_FilePath.ReverseFind(_T('\\')); 

    m_FilePath = m_FilePath.Left(m_iPosIndex) + _T("\\Log");

    return m_FilePath;
}

BOOL CLogFile::WriteLog(CString LogText)
{
    try
    {
        CFile m_File;
        CStdioFile m_SFile;
        CFileFind m_FileFind;
        CString strLog;
        CString m_sFileName = GetFileName();
        CString m_sFilePath = GetFilePath();
        CString strTime = CTime::GetCurrentTime().Format(_T("[%Y-%m-%d %H:%M:%S] "));
        /*
        格式符号说明 
        %a —— 星期(缩写英文),如Fri; 
        %A —— 星期(全写英文),如Friday 
        %b —— 月份(缩写英文),如Oct 
        %B —— 月份(全写英文),如 October 
        %c  —— 月/日/年 时:分:秒,如 10/13/06 19:17:17 
        %d  —— 日期(1 ~ 31) 
        %H  —— 时(24小时制)(0 ~ 23) 
        %I    —— 时(12小时制)(0 ~ 12) 
        %j    —— 一年当中的第几天,(1 ~ 366) 
        %m  —— 月份(数字 1 ~ 12) 
        %M  —— 分(0 ~ 59) 
        %p  —— 12小时中的A M/PM指示,或者AM,或者PM 
        %S  —— 秒(0 ~ 59) 
        %U  —— 一年中的第几周,星期日作为每周的第一天(0 ~ 53) 
        %w  —— 星期(数字表示,0 ~ 6,0代表星期日) 
        %W —— 一年中的第几周,星期一作为每周的第一天(0 ~ 53) 
        %x   —— 月/日/年,%c的前半段
        */
        //组合写入字符串
        strLog += strTime;
        strLog += LogText;

        if(!m_FileFind.FindFile(m_sFilePath))
        {
            CreateDirectory(m_sFilePath,NULL);
        }

        if(!m_SFile.Open(m_sFilePath + _T("\\") +m_sFileName,CFile::modeReadWrite))
        {
            m_SFile.Open(m_sFilePath + _T("\\") + m_sFileName,CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary);
        }

        m_SFile.SeekToEnd(); 

        //written by jiftle 处理UNICODE下乱码
#ifdef UNICODE 
        CString strTmp = strLog;
        int len = 0;
        char *buf = NULL;
        len = WideCharToMultiByte(CP_ACP,0,strTmp,strTmp.GetLength(),NULL,0,NULL,NULL)+1;
        buf	= new char[len];
        memset(buf,0,len);
        WideCharToMultiByte(CP_ACP,0,strTmp,strTmp.GetLength(),buf,len-1,NULL,NULL);
#else
        CString strTmp = strLog;
        char *buf = NULL;
        int len=0;
        len = strTmp.GetLength()+1;//多分配一个存放结束符号
        buf = new char[len];
        memset(buf,0,len);
        buf=strTmp.GetBuffer();
#endif

        m_SFile.Write(buf,strlen(buf));
        m_SFile.Close();
    }
    catch(CFileException fileException)
    {
        return false;
    }

    return true;
}

在头文件中加入如下

class CLogFile  
{
public:
    CLogFile();
    virtual ~CLogFile();
    static CString GetFileName();
    static CString GetFilePath();
    static BOOL WriteLog(CString LogText);
};

 

本文出自:http://blog.weka.cc/cpp/vc-log/

VC实现Http Put方法

#include <Wininet.h>
                   
#pragma comment(lib, "Wininet.lib")
BOOL HttpRequestPut(LPCTSTR pHomeUrl, LPCTSTR pPageUrl, LONG nPort,
    LPCTSTR pFile, CString *psRes, PBOOL pbExit)
{
    LPINTERNET_BUFFERS pBufferIn = new INTERNET_BUFFERS;
    ZeroMemory(pBufferIn, sizeof(INTERNET_BUFFERS));
    LPBYTE pBuf = new BYTE[1024];
    HINTERNET hInternet = NULL;
    HINTERNET hSession = NULL;
    HINTERNET hRequest = NULL;
    DWORD dwBytesRead;
    DWORD dwBytesWritten;
    HANDLE hFile = INVALID_HANDLE_VALUE;
    CString sFormat(_T("Connection: Keep-Alive\r\n"));
    sFormat += _T("Content-Type: application/octet-stream\r\n");
    sFormat += _T("Content-Length: %u\r\n");
    sFormat += _T("User-Agent:Test\r\n");
    sFormat += _T("Host: %s:%u\r\n");
    sFormat += _T("Accept: *.*,*/*\r\n");
    sFormat += _T("\r\n");
    CString sHeader(_T(""));
    CString sRes(_T(""));
                   
    do
    {
        hInternet = InternetOpen(_T("Mozilla/4.0 (compatible; Indy Library)"),  
      INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); 
        if( NULL == hInternet )
        { 
            sRes.Format(_T("Open link error. ErrCode=[%u]"), GetLastError());
            break;
        }
                   
        hSession = InternetConnect(hInternet, pHomeUrl, (INTERNET_PORT)nPort,
            NULL, NULL,INTERNET_SERVICE_HTTP, INTERNET_FLAG_NO_CACHE_WRITE, 0);
        hRequest = HttpOpenRequest(hSession, _T("PUT"), pPageUrl,
            NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);
        if( FALSE == hRequest )
        {
            sRes.Format(_T("Open request handle error. ErrCode=[%u]"),
                GetLastError());
            break;
        }
                   
        hFile = CreateFile(pFile, GENERIC_READ, FILE_SHARE_READ, NULL,
             OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
        if( hFile == INVALID_HANDLE_VALUE )
        {
            sRes.Format(_T("Open File error. ErrCode=[%u] File=[%s]"),
                GetLastError(), pFile);
            break;
        }
                   
        pBufferIn->dwStructSize = sizeof(INTERNET_BUFFERS);
        pBufferIn->dwBufferTotal = GetFileSize(hFile, NULL);
        sHeader.Format(sFormat, pBufferIn->dwBufferTotal, pHomeUrl, nPort);
        pBufferIn->lpcszHeader = sHeader;
        pBufferIn->dwHeadersLength = sHeader.GetLength();
                   
        if( FALSE ==
            HttpSendRequestEx(hRequest, pBufferIn, NULL, HSR_INITIATE, 0) )
        {
            sRes.Format(_T("Send request error."));
            break;
        }
                   
        DWORD dwSendSize = 0;
        while( dwSendSize < pBufferIn->dwBufferTotal )
        {
            if( (NULL!=pbExit) && (FALSE!=(*pbExit)) )
            {
                sRes.Format(_T("Stop upload because receive exit cmd."));
                break;
            }
                   
            if( FALSE == ReadFile( hFile, pBuf, 1024, &dwBytesRead, NULL) )
            {
                sRes.Format(_T("Read File error. ErrCode=[%u] File=[%s]"),
                    GetLastError(), pFile);
                break;
            }
                   
            if( FALSE == InternetWriteFile(hRequest, pBuf, dwBytesRead,
                  &dwBytesWritten) )
            {// ERROR_INTERNET_CONNECTION_ABORTED
                sRes.Format(_T("Upload File error. ErrCode=[%u] File=[%s]"),            
            GetLastError(), pFile);
                break;
            }
                   
            dwSendSize += dwBytesWritten;
        }
                   
        if( FALSE == HttpEndRequest(hRequest, NULL, 0, 0) )
        {
            sRes.Format(_T("End request error. ErrCode=[%u] File=[%s]"),
                GetLastError(), pFile);
        }
     
    }while(FALSE);
                   
    if( hFile != INVALID_HANDLE_VALUE )
    {
        CloseHandle(hFile);
    }
    if( hRequest )
    {
        InternetCloseHandle(hRequest);
    }
    if( hSession )
    {
        InternetCloseHandle(hSession);
    }
    if( hInternet )
    {
        InternetCloseHandle(hInternet);
    }
                   
    delete []pBuf;
    delete pBufferIn;
                   
    if( NULL != psRes )
    {
        *psRes = sRes;
    }
                   
    return sRes.IsEmpty();
}

 

本文出自:https://blog.csdn.net/mrxyz098/article/details/27991335

国密SM3密码杂凑算法原理及实现(附源码)

这部分实现的源码完全参考官方文档的算法描述,连变量名也尽可能和官方文档中的变量保持一致,方便学习。

另外, 代码封装的SM3哈希调用接口参考了openssl官方的接口,完全兼容,无缝对接。会使用这里的接口,就会使用openssl的库函数接口,甚至连代码都不需要修改。

除了实现的源码外,还另外附带了一个测试例子,这个测试例子不仅仅是用于测试哈希算法的实现是否正确,还可以提供了”-f”/”-s”等选项用于对任意文件和字符串进行哈希,因此作为一个工具使用,类似系统内置的md5sum/sha1sum。

头文件sm3.h

/*
 * @        file: sm3.h
 * @ description: header file for sm3.c
 * @      author: Gu Yongqiang
 * @        blog: https://blog.csdn.net/guyongqiangx
 */
#ifndef __ROCKY_SM3__H
#define __ROCKY_SM3__H

#define ERR_OK           0
#define ERR_ERR         -1  /* generic error */
#define ERR_INV_PARAM   -2  /* invalid parameter */
#define ERR_TOO_LONG    -3  /* too long */
#define ERR_STATE_ERR   -4  /* state error */

typedef unsigned char      uint8_t;
typedef unsigned short     uint16_t;
typedef unsigned int       uint32_t;
typedef unsigned long long uint64_t;

typedef struct sm3_context {
    /* message total length in bytes */
    uint64_t total;

    /* intermedia hash value for each block */
    struct {
        uint32_t a;
        uint32_t b;
        uint32_t c;
        uint32_t d;
        uint32_t e;
        uint32_t f;
        uint32_t g;
        uint32_t h;
    }hash;

    /* last block */
    struct {
        uint32_t used;     /* used bytes */
        uint8_t  buf[64];  /* block data buffer */
    }last;
}SM3_CTX;

/* https://www.openssl.org/docs/man1.1.1/man3/SHA256_Final.html */

int SM3_Init(SM3_CTX *c);
int SM3_Update(SM3_CTX *c, const void *data, size_t len);
int SM3_Final(unsigned char *md, SM3_CTX *c);
unsigned char *SM3(const unsigned char *d, size_t n, unsigned char *md);
#endif

代码文件sm3.c

/*
 * @        file: sm3.c
 * @ description: implementation for the SM3 Cryptographic Hash Algorithm
 * @      author: Gu Yongqiang
 * @        blog: https://blog.csdn.net/guyongqiangx
 */
#include <stdio.h>
#include <string.h>

#include "utils.h"
#include "sm3.h"

// #define DEBUG

#ifdef DEBUG
#define DBG(...) printf(__VA_ARGS__)
#define DUMP_SCHED_DATA 1
#define DUMP_BLOCK_DATA 1
#define DUMP_BLOCK_HASH 1
#define DUMP_ROUND_DATA 1
#else
#define DBG(...)
#define DUMP_SCHED_DATA 0
#define DUMP_BLOCK_DATA 0
#define DUMP_BLOCK_HASH 0
#define DUMP_ROUND_DATA 0
#endif

#define HASH_BLOCK_SIZE		    64	/* 512 bits = 64 Bytes */
#define HASH_LEN_SIZE	 	    8	/* 64 bits = 8 bytes */
#define HASH_LEN_OFFSET         (HASH_BLOCK_SIZE - HASH_LEN_SIZE)

#define HASH_DIGEST_SIZE        32 /* 256 bits = 32 bytes */

#define HASH_PADDING_PATTERN 	0x80
#define HASH_ROUND_NUM			64

/* SM3 Constants */
static uint32_t T[2] = 
{
    0x79CC4519, 0x7A879D8A
};

/* ROTate Left (circular left shift) */
static uint32_t ROTL(uint32_t x, uint8_t shift)
{
    shift %= 32;
    return (x << shift) | (x >> (32 - shift));
}

static uint32_t FF(uint32_t x, uint32_t y, uint32_t z, uint32_t j)
{
    if (j<16) /* 0 <= j <= 15 */
    {
        return x ^ y ^ z;
    }
    else /* 16 <= j <= 63 */
    {
        return (x & y) | (x & z) | (y & z);
    }
}

static uint32_t GG(uint32_t x, uint32_t y, uint32_t z, uint32_t j)
{
    if (j<16) /* 0 <= j <= 15 */
    {
        return x ^ y ^ z;
    }
    else /* 16 <= j <= 63 */
    {
        return (x & y) | (~x & z);
    }
}

/* P0, Permutation 0 */
static uint32_t P0(uint32_t x)
{
    return x ^ ROTL(x, 9) ^ ROTL(x, 17);
}

/* P1, Permutation 1 */
static uint32_t P1(uint32_t x)
{
    return x ^ ROTL(x, 15) ^ ROTL(x, 23);
}

int SM3_Init(SM3_CTX *c)
{
    if (NULL == c)
    {
        return ERR_INV_PARAM;
    }

    memset(c, 0, sizeof(SM3_CTX));

    /* Initial Value for SM3 */
    c->hash.a = 0x7380166f;
    c->hash.b = 0x4914b2b9;
    c->hash.c = 0x172442d7;
    c->hash.d = 0xda8a0600;
    c->hash.e = 0xa96f30bc;
    c->hash.f = 0x163138aa;
    c->hash.g = 0xe38dee4d;
    c->hash.h = 0xb0fb0e4e;

    return ERR_OK;
}

static int SM3_PrepareScheduleWord(const uint32_t *block, uint32_t *W, uint32_t *Wp)
{
    uint32_t j;

    if ((NULL == block) || (NULL == W) || (NULL == Wp))
    {
        return ERR_INV_PARAM;
    }

    /* Array W */
    for (j=0; j<(HASH_ROUND_NUM+4); j++)
    {
        if (j<=15) /*  0 <= j <= 15 */
            W[j] = be32toh(block[j]);
        else	   /* 16 <= j <= 67 */
            W[j] = P1(W[j-16] ^ W[j-9] ^ ROTL(W[j-3],15)) ^ ROTL(W[j-13],7) ^ W[j-6];
    }

    /* Array W Prime */
    for (j=0; j<HASH_ROUND_NUM; j++)
    {
        Wp[j] = W[j] ^ W[j+4];
    }

#if (DUMP_SCHED_DATA == 1)
    printf("          W1...W67:\n");
    for (j=0; j<(HASH_ROUND_NUM+4); j++)
    {
        if (j%8 == 0) /* line indent */
        {
            printf("          ");
        }

        printf("%08x ", W[j]);

        if (j%8 == 7)
        {
            printf("\n");
        }
        else if (j == (HASH_ROUND_NUM+4-1))
        {
            printf("\n"); /* last one */
        }
    }

    printf("          W'1...W'63:\n");
    for (j=0; j<HASH_ROUND_NUM; j++)
    {
        if (j%8 == 0) /* line indent */
        {
            printf("          ");
        }

        printf("%08x ", Wp[j]);

        if (j%8 == 7)
        {
            printf("\n");
        }
        else if (j == HASH_ROUND_NUM-1)
        {
            printf("\n"); /* last one */
        }
    }
#endif

    return ERR_OK;
}

static int SM3_ProcessBlock(SM3_CTX *ctx, const void *block)
{
    uint32_t j;
    uint32_t W[HASH_ROUND_NUM+4], Wp[HASH_ROUND_NUM];
    uint32_t SS1, SS2;
    uint32_t TT1, TT2;
    uint32_t A, B, C, D, E, F, G, H;

    if ((NULL == ctx) || (NULL == block))
    {
        return ERR_INV_PARAM;
    }

#if (DUMP_BLOCK_DATA == 1)
    DBG("---------------------------------------------------------\n");
    DBG("   BLOCK: %llu\n", ctx->total/HASH_BLOCK_SIZE);
    DBG("    DATA:\n");
    print_buffer(block, HASH_BLOCK_SIZE, "    ");
#endif

    /* prepare schedule word */
    SM3_PrepareScheduleWord(block, W, Wp);

    A = ctx->hash.a;
    B = ctx->hash.b;
    C = ctx->hash.c;
    D = ctx->hash.d;
    E = ctx->hash.e;
    F = ctx->hash.f;
    G = ctx->hash.g;
    H = ctx->hash.h;

#if (DUMP_BLOCK_HASH == 1)
    DBG("      IV: %08x %08x %08x %08x %08x %08x %08x %08x\n",
        ctx->hash.a, ctx->hash.b, ctx->hash.c, ctx->hash.d, ctx->hash.e, ctx->hash.f, ctx->hash.g, ctx->hash.h);
#endif

    for (j=0; j<HASH_ROUND_NUM; j++)
    {
        SS1 = ROTL(ROTL(A, 12) + E + ROTL(T[j<16?0:1], j), 7);
        SS2 = SS1 ^ ROTL(A, 12);
        TT1 = FF(A, B, C, j) + D + SS2 + Wp[j];
        TT2 = GG(E, F, G, j) + H + SS1 + W[j];
          D = C;
          C = ROTL(B, 9);
          B = A;
          A = TT1;
          H = G;
          G = ROTL(F, 19);
          F = E;
          E = P0(TT2);

#if (DUMP_ROUND_DATA == 1)
#if 1 /* Don't show temp variables: SS1/SS2/TT1/TT2/W/W' */
        DBG("      %02d: A=0x%08x, B=0x%08x, C=0x%08x, D=0x%08x, E=0x%08x, F=0x%08x, G=0x%08x, H=0x%08x\n", \
                j, A, B, C, D, E, F, G, H);
#else
        DBG("      %02d: SS1=0x%08x, SS2=0x%08x, TT1=0x%08x, TT2=0x%08x, W=0x%08x, Wp=0x%08x\n"\
            "         A=0x%08x,    B=0x%08x,   C=0x%08x,   D=0x%08x, E=0x%08x, F=0x%08x, G=0x%08x, H=0x%08x\n", \
                j, SS1, SS2, TT1, TT2, W[j], Wp[j], A, B, C, D, E, F, G, H);
#endif
#endif
    }

    ctx->hash.a ^= A;
    ctx->hash.b ^= B;
    ctx->hash.c ^= C;
    ctx->hash.d ^= D;
    ctx->hash.e ^= E;
    ctx->hash.f ^= F;
    ctx->hash.g ^= G;
    ctx->hash.h ^= H;

#if (DUMP_BLOCK_HASH == 1)
    DBG("    HASH: %08x %08x %08x %08x %08x %08x %08x %08x\n",
        ctx->hash.a, ctx->hash.b, ctx->hash.c, ctx->hash.d, ctx->hash.e, ctx->hash.f, ctx->hash.g, ctx->hash.h);
#endif

    return ERR_OK;
}


int SM3_Update(SM3_CTX *c, const void *data, size_t len)
{
    uint32_t copy_len = 0;

    if ((NULL == c) || (NULL == data))
    {
        return ERR_INV_PARAM;
    }

    /* has used data */
    if (c->last.used != 0)
    {
        /* less than 1 block in total, combine data */
        if (c->last.used + len < HASH_BLOCK_SIZE)
        {
            memcpy(&c->last.buf[c->last.used], data, len);
            c->last.used += len;

            return ERR_OK;
        }
        else /* more than 1 block */
        {
            /* process the block in context buffer */
            copy_len = HASH_BLOCK_SIZE - c->last.used;
            memcpy(&c->last.buf[c->last.used], data, copy_len);
            SM3_ProcessBlock(c, &c->last.buf);
            c->total += HASH_BLOCK_SIZE;

            data = (uint8_t *)data + copy_len;
            len -= copy_len;

            /* reset context buffer */
            memset(&c->last.buf[0], 0, HASH_BLOCK_SIZE);
            c->last.used = 0;
        }
    }

    /* less than 1 block, copy to context buffer */
    if (len < HASH_BLOCK_SIZE)
    {
        memcpy(&c->last.buf[c->last.used], data, len);
        c->last.used += len;

        return ERR_OK;
    }
    else
    {
        /* process data blocks */
        while (len >= HASH_BLOCK_SIZE)
        {
            SM3_ProcessBlock(c, data);
            c->total += HASH_BLOCK_SIZE;

            data = (uint8_t *)data + HASH_BLOCK_SIZE;
            len -= HASH_BLOCK_SIZE;
        }

        /* copy rest data to context buffer */
        memcpy(&c->last.buf[0], data, len);
        c->last.used = len;
    }

    return ERR_OK;
}

int SM3_Final(unsigned char *md, SM3_CTX *c)
{
    uint32_t *temp;
    //uint64_t *buf;

    if ((NULL == c) || (NULL == md))
    {
        return ERR_INV_PARAM;
    }

    /* Last block should be less thant HASH_BLOCK_SIZE - HASH_LEN_SIZE */
    if (c->last.used >= (HASH_BLOCK_SIZE - HASH_LEN_SIZE))
    {
        c->total += c->last.used;

        /* one more block */
        c->last.buf[c->last.used] = HASH_PADDING_PATTERN;
        c->last.used++;

        memset(&c->last.buf[c->last.used], 0, HASH_BLOCK_SIZE - c->last.used);
        SM3_ProcessBlock(c, &c->last.buf);

        memset(&c->last.buf[0], 0, HASH_BLOCK_SIZE - HASH_LEN_SIZE);
        c->last.used = 0;

        /* save length */
        //buf = (uint64_t *)&(c->last.buf[HASH_LEN_OFFSET]);
        //*buf = htobe64(c->total << 3);
        temp = (uint32_t *)&(c->last.buf[HASH_LEN_OFFSET]);
        temp[0] = htobe32((c->total << 3) >> 32 & 0xFFFFFFFF);
        temp[1] = htobe32((c->total << 3) & 0xFFFFFFFF);

        SM3_ProcessBlock(c, &c->last.buf);
    }
    else /* 0 <= last.used < HASH_BLOCK_SIZE - HASH_LEN_SIZE */
    {
        c->total += c->last.used;

        /* one more block */
        c->last.buf[c->last.used] = HASH_PADDING_PATTERN;
        c->last.used++;

        /* padding 0s */
        memset(&c->last.buf[c->last.used], 0, HASH_BLOCK_SIZE - HASH_LEN_SIZE - c->last.used);

        /* save length */
        //buf = (uint64_t *)&(c->last.buf[HASH_LEN_OFFSET]);
        //*buf = htobe64(c->total << 3);
        temp = (uint32_t *)&(c->last.buf[HASH_LEN_OFFSET]);
        temp[0] = htobe32((c->total << 3) >> 32 & 0xFFFFFFFF);
        temp[1] = htobe32((c->total << 3) & 0xFFFFFFFF);

        SM3_ProcessBlock(c, &c->last.buf);
    }

    temp = (uint32_t *)md;
    temp[0] = htobe32(c->hash.a);
    temp[1] = htobe32(c->hash.b);
    temp[2] = htobe32(c->hash.c);
    temp[3] = htobe32(c->hash.d);
    temp[4] = htobe32(c->hash.e);
    temp[5] = htobe32(c->hash.f);
    temp[6] = htobe32(c->hash.g);
    temp[7] = htobe32(c->hash.h);

    return ERR_OK;
}

unsigned char *SM3(const unsigned char *d, size_t n, unsigned char *md)
{
    SM3_CTX c;

    if ((NULL == d) || (NULL == md))
    {
        return NULL;
    }

    SM3_Init(&c);
    SM3_Update(&c, d, n);
    SM3_Final(md, &c);

    return md;
}

 

本文出自:https://blog.csdn.net/guyongqiangx/article/details/118061218

C/C++生成JSON文件

这里我们就是用一个开源库 cJSON(方法多种多样也可以用其他的库)来生成一个json文件。

如下是我们要生成的一个json文件

{
    "roomNumber" : "B06",          // 宿舍编号
    "peopleCount" : 6,				// 宿舍人数
    "roomFreeTabels" : 0,			// 宿舍空闲床位
    "roomElemName" : [				// 宿舍人的姓名
    	"libero", 
    	"rock",
    	"martin",
    	"sky",
    	"bingo",
    	"janny"
    ]
}

代码

#include <iostream>
#include <Windows.h>
#include <fstream>
#include "cJSON.h"
 
using namespace std;
 
#define _CRT_SECURE_NO_WARNINGS
#define OPEN_MAX_TIMES 5
 
int main(int argc, const char* argv[])
{
    cJSON* root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "roomNumber", cJSON_CreateString("B06"));
    cJSON_AddItemToObject(root, "peopleCount", cJSON_CreateNumber(6));
    cJSON_AddItemToObject(root, "roomFreeTabels", cJSON_CreateNumber(0));
 
    // 姓名数组 这里可以用循环代替 这样一个个写太low了
    // 但是为了让大家更清晰的看还是一个个写
    cJSON* array = cJSON_CreateArray();
    cJSON_AddItemToArray(array, cJSON_CreateString("libero"));
    cJSON_AddItemToArray(array, cJSON_CreateString("rock"));
    cJSON_AddItemToArray(array, cJSON_CreateString("martin"));
    cJSON_AddItemToArray(array, cJSON_CreateString("sky"));
    cJSON_AddItemToArray(array, cJSON_CreateString("bingo"));
    cJSON_AddItemToArray(array, cJSON_CreateString("janny"));
 
    // 把数组加紧 大的对象中
    cJSON_AddItemToObject(root, "roomElemName", array);
 
    // 写道文件中去
    char* buf = cJSON_Print(root);
 
    ofstream fout;
    fout.open("cjosn.json", ios_base::out | ios_base::binary);  // 二进制的写
    int count = 0;
    while (!fout.is_open() && count < OPEN_MAX_TIMES) {
        cerr << "open file error.has " << OPEN_MAX_TIMES - (++count) 
            << "times retry" << endl;
    }
 
    do{
        if (count == 5) {
            cerr << "file open error total" << endl;
            break;
        }
        fout << buf << flush;
        fout.close();
    } while (0);
 
    cJSON_Delete(root);
 
    system("pause");
    return 0;
}

 

本文出自:https://blog.csdn.net/qq_44065088/article/details/107374571

VC++ 下处理 UTF8 编码的字符串

void UTF8toANSI(CString &strUTF8)
{
//获取转换为多字节后需要的缓冲区大小,创建多字节缓冲区
UINT nLen = MultiByteToWideChar(CP_UTF8,NULL,strUTF8,-1,NULL,NULL);
WCHAR *wszBuffer = new WCHAR[nLen+1];
nLen = MultiByteToWideChar(CP_UTF8,NULL,strUTF8,-1,wszBuffer,nLen);
wszBuffer[nLen] = 0;

nLen = WideCharToMultiByte(936,NULL,wszBuffer,-1,NULL,NULL,NULL,NULL);
CHAR *szBuffer = new CHAR[nLen+1];
nLen = WideCharToMultiByte(936,NULL,wszBuffer,-1,szBuffer,nLen,NULL,NULL);
szBuffer[nLen] = 0;
strUTF8 = szBuffer;
//清理内存
delete []szBuffer;
delete []wszBuffer;
}
//ANSI转UTF8
void ANSItoUTF8(CString &strAnsi)
{
//获取转换为宽字节后需要的缓冲区大小,创建宽字节缓冲区,936为简体中文GB2312代码页
UINT nLen = MultiByteToWideChar(936,NULL,strAnsi,-1,NULL,NULL);
WCHAR *wszBuffer = new WCHAR[nLen+1];
nLen = MultiByteToWideChar(936,NULL,strAnsi,-1,wszBuffer,nLen);
wszBuffer[nLen] = 0;
//获取转为UTF8多字节后需要的缓冲区大小,创建多字节缓冲区
nLen = WideCharToMultiByte(CP_UTF8,NULL,wszBuffer,-1,NULL,NULL,NULL,NULL);
CHAR *szBuffer = new CHAR[nLen+1];
nLen = WideCharToMultiByte(CP_UTF8,NULL,wszBuffer,-1,szBuffer,nLen,NULL,NULL);
szBuffer[nLen] = 0;
strAnsi = szBuffer;
//内存清理
delete []wszBuffer;
delete []szBuffer;
}

在windows下打开一个记事本,保存文件,下面有四种编码选择。ANSI,也就是多字节字符集,在VC中也就是CHAR(char)字符串。Unicode,就是UTF16,在VC中也就是WCHAR(wchar_t)字符串。Unicode big endian ,就是UTF32,这种编码用的比较少。UTF8,网页上几乎都是用UTF8,UTF8用1-4个字节来编码所有的字符,英文只需要1个 字节,中文需要3-4个字节。比起UTF16来说,UTF8这样可以尽可能的节省网络带宽,因为在网络上传输的字符,大部分以英文为主。UTF16至少是2个字节,部分字符4个字节。

如果我们写一个VC程序,从获取HTML网页数据,这些数据的编码是UTF8的,获取到我们VC程序中的CHAR字符数组中时就会发现,英文可以正常显示,中文全部乱码了。因为我们的CHAR型字符串用的是ANSI编码。要想把UTF8转换为ANSI,一般有两种方法。一种是手工写代码实现,百度上搜索可以发现很多资料,透彻了解这些字符集编码后,可以手工来实现转换,网上也有很多别人写好的转换函数。一种方法就是借助第三方函数库。由于我们在windows平台下编写程序,我们可以使用API函数来转换MultiByteToWideChar和WideCharToMultiByte。使用这个函数,我们得进行两次转换,先用MultiByteToWideChar把UTF8编码的CHAR字符串转换成WCHAR字符串,第一个参数要注明我们要转换的代码页为CP_UTF8,即UTF8的意思。然后用WideCharToMultiByte吧WCHAR字符串转换成CHAR字符串,第一个参数使用936,936代码页的意思是简体中文。有关代码页的知识可以百度百科一下。

本文出自:https://blog.csdn.net/xuexiiphone/article/details/51252778

分割字符串的AfxExtractSubString函数

函数原型:

BOOL AfxExtractSubString(CString& rString, LPCTSTR lpszFullString, int iSubString, TCHAR chSep = ‘\n’)

参数说明:

rString  保存输出的子字符串

lpszFullString  待分割的字符串

iSubString  提取的子字符串的序号,从0开始。假如你想提取第3段,该参数就输入2

chSep  用于分割的字符,默认的是’\n’

返回值:分割成功,就返回TRUE;iSubString越界,则返回FALSE

举例说明:

CString szGet;	
CString szText = "var hq_str_sh600736=\"苏州高新,5.33,5.32,5.70,5.85,5.32,5.71,5.72,56939555,323766177,92561,5.71,121300,5.70,57200,5.69,34600,5.68,18600,5.67,130327,5.72,177801,5.73,40999,5.74,194908,5.75,69600,5.76,2011-08-12,15:03:07\";";

AfxExtractSubString(szGet, szText, 1, ',');	//取回 5.33
AfxExtractSubString(szGet, szText, 2, ',');	//取回 5.32
AfxExtractSubString(szGet, szText, 3, ',');	//取回 5.70
//想要取回苏州高新
AfxExtractSubString(szGet, szText, 0, ',');	//先取回var hq_str_sh600736="苏州高新
AfxExtractSubString(szGet, szGet, 1, '\"');	//取回 苏州高新

注意:用于分割的只能是字符,不能是字符串。

多个字符使用_tcstok函数,另外可以使用find函数自己写.

本文出自:http://www.blogjava.net/CrackRen/archive/2011/08/13/361964.html

VC修改文件时间属性(修改/访问时间)

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include <Windows.h>
#include <time.h>
 
 
#include <sys/types.h>
#include <sys/utime.h>
 
int DateWeek(int year, int month, int day)
{
    if (month==1||month==2)
    {
        year -=1;
        month +=12;
    }
    return (day+1+2*month+3*(month+1)/5+year+(year/4)-year/100+year/400)%7;
}
int sum_day(int year,int month,int day)
{
    int days = day;
    int day_month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
    int i;
    for(i=1;i<month;i++)days += day_month[i];
 
    int leap=0;
    if((year%4==0&&year%100==0)||(year%400==0))leap=1;
    if(leap && month>=3)days=days+1;
 
    return days;
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    SYSTEMTIME st;
    FILETIME ft;
    st.wYear = 2007;
    st.wMonth = 8;
    st.wDay = 25;
    st.wHour = 15;
    st.wDayOfWeek = 5;
    st.wMinute =1;
    st.wSecond = 1;
    st.wMilliseconds = 1;
#if 0
    _utimbuf mvTime;
    time_t rawtime;
    struct tm *timeinfo;
    timeinfo = localtime(&rawtime);		
 
    timeinfo->tm_hour = st.wHour;
    timeinfo->tm_isdst = 0;
    timeinfo->tm_mday = st.wDay;
    timeinfo->tm_min = st.wMinute;
    timeinfo->tm_mon = st.wMonth;
    timeinfo->tm_sec = st.wSecond;	
    timeinfo->tm_wday = DateWeek(st.wYear,st.wMonth,st.wDay);
    timeinfo->tm_yday = sum_day(st.wYear,st.wMonth,st.wDay);
    timeinfo->tm_year = st.wYear - 1900;
 
    mvTime.actime = mktime(timeinfo);
    mvTime.modtime = mktime(timeinfo);
    _wutime(TEXT("F:/type.txt"),&mvTime);
#else
    HANDLE hFile = CreateFile(TEXT("F:/type.txt"), 
        GENERIC_READ|GENERIC_WRITE,
        FILE_SHARE_READ|FILE_SHARE_DELETE, 
        NULL, OPEN_EXISTING, 
        FILE_FLAG_BACKUP_SEMANTICS, NULL); 	
    if(hFile!=INVALID_HANDLE_VALUE)
    {
        SystemTimeToFileTime(&st,&ft);
        int res=SetFileTime(hFile,&ft,&ft,&ft);
        CloseHandle(hFile);
    }
#endif
}

,SystemTimeToFileTime接口计算出错。不知道具体原因。然后Google找到另外一种解决办法就是用utime来修改(修改/访问)时间使用_wutime修改的代码

本文出自:https://blog.csdn.net/evea804/article/details/32139941

Fixed a BUG of VC++ 6.0

MSDN documentation states that for files larger than 4 gigabytes,there is the CFileFind::GetLength64() function that returns the size as 64Bit number.But the function just return a wrong 32Bit number. Damn Microsoft!

Solution: write a derived class(CMyFtpFileFind) from CFtpFileFind,and implementing the GetLength64() member function correctly. Replace this derived class with CFtpFileFind.

Reference: http://www.codeproject.com/KB/bugs/getlength64bug.asp.aspx?print=true
Last version: https://gist.github.com/978421

Source code as following text:

class CMyFtpFileFind : public CFtpFileFind
{
public :
CMyFtpFileFind ( CFtpConnection * pConnection , DWORD dwContext = 1 ) : CFtpFileFind ( pConnection , dwContext )
{
}

virtual ~ CMyFtpFileFind () { }

__int64 GetLength64 () const
{
ASSERT ( m_hContext != NULL );
ASSERT_VALID ( this );
unsigned __int64 uRet = 0 ;

if ( m_pFoundInfo != NULL )
{
unsigned __int64 uFileSizeLow = (( LPWIN32_FIND_DATA ) m_pFoundInfo ) -> nFileSizeLow ;
unsigned __int64 uFileSizeHigh = (( LPWIN32_FIND_DATA ) m_pFoundInfo ) -> nFileSizeHigh ;
uRet = uFileSizeLow + ( uFileSizeHigh << 32 );
}

return uRet ;
}

}; // CMyFtpFileFind

 

本文出自:https://blog.csdn.net/iteye_11067/article/details/82066315

用cfile类读取大文件

/********** cfile64.h  *********/

 

class CFile64 : public CFile
{
public:

// Attributes
ULONGLONG GetPosition();


// Overridables

virtual ULONGLONG Seek(LONGLONG lOff, UINT nFrom);
virtual void SetLength(ULONGLONG dwNewLen);
ULONGLONG GetLength() ;

virtual void LockRange(ULONGLONG dwPos, ULONGLONG dwCount);
virtual void UnlockRange(ULONGLONG dwPos, ULONGLONG dwCount);


};

 

 

/*************** cfile64.cpp ***************/
#include "stdafx.h"
#include "file64.h"


// CFile64 implementation


ULONGLONG CFile64::Seek(LONGLONG lOff, UINT nFrom)
{
ASSERT_VALID(this);
ASSERT((HANDLE)m_hFile != INVALID_HANDLE_VALUE);
ASSERT(nFrom == begin || nFrom == end || nFrom == current);
ASSERT(begin == FILE_BEGIN && end == FILE_END && current == FILE_CURRENT);

   LARGE_INTEGER liOff;

   liOff.QuadPart = lOff;
liOff.LowPart = ::SetFilePointer((HANDLE)m_hFile, liOff.LowPart, &liOff.HighPart,
   (DWORD)nFrom);
if (liOff.LowPart  == (DWORD)-1)
   if (::GetLastError() != NO_ERROR)
     CFileException::ThrowOsError((LONG)::GetLastError(), m_strFileName);

return liOff.QuadPart;
}

ULONGLONG CFile64::GetPosition() 
{
ASSERT_VALID(this);
ASSERT((HANDLE)m_hFile != INVALID_HANDLE_VALUE);

   LARGE_INTEGER liPos;
   liPos.QuadPart = 0;
liPos.LowPart = ::SetFilePointer((HANDLE)m_hFile, liPos.LowPart, &liPos.HighPart , FILE_CURRENT);
if (liPos.LowPart == (DWORD)-1)
   if (::GetLastError() != NO_ERROR)
     CFileException::ThrowOsError((LONG)::GetLastError(), m_strFileName);

return liPos.QuadPart;
}

void CFile64::LockRange(ULONGLONG dwPos, ULONGLONG dwCount)
{
ASSERT_VALID(this);
ASSERT((HANDLE)m_hFile != INVALID_HANDLE_VALUE);

   ULARGE_INTEGER liPos;
   ULARGE_INTEGER liCount;

   liPos.QuadPart = dwPos;
   liCount.QuadPart = dwCount;
if (!::LockFile((HANDLE)m_hFile, liPos.LowPart, liPos.HighPart, liCount.LowPart, 
   liCount.HighPart))
   {
  CFileException::ThrowOsError((LONG)::GetLastError(), m_strFileName);
   }
}

void CFile64::UnlockRange(ULONGLONG dwPos, ULONGLONG dwCount)
{
ASSERT_VALID(this);
ASSERT((HANDLE)m_hFile != INVALID_HANDLE_VALUE);

   ULARGE_INTEGER liPos;
   ULARGE_INTEGER liCount;

   liPos.QuadPart = dwPos;
   liCount.QuadPart = dwCount;
if (!::UnlockFile((HANDLE)m_hFile, liPos.LowPart, liPos.HighPart, liCount.LowPart,
   liCount.HighPart))
   {
  CFileException::ThrowOsError((LONG)::GetLastError(), m_strFileName);
   }
}

void CFile64::SetLength(ULONGLONG dwNewLen)
{
ASSERT_VALID(this);
ASSERT((HANDLE)m_hFile != INVALID_HANDLE_VALUE);

Seek(dwNewLen, (UINT)begin);

if (!::SetEndOfFile((HANDLE)m_hFile))
  CFileException::ThrowOsError((LONG)::GetLastError(), m_strFileName);
}

ULONGLONG CFile64::GetLength() 
{
ASSERT_VALID(this);

   ULARGE_INTEGER liSize;
   liSize.LowPart = ::GetFileSize((HANDLE)m_hFile, &liSize.HighPart);
   if (liSize.LowPart == (DWORD)-1)
   if (::GetLastError() != NO_ERROR)
   CFileException::ThrowOsError((LONG)::GetLastError(), m_strFileName);

return liSize.QuadPart;
}


/

LONGLONG是64位整型,这样在理论上可支持的最大文件为18000000000GB,你也可以根据自己的需要重载CFile的其他函数

本文出自:https://blog.csdn.net/jrt88/article/details/4392838/