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