将JSON文件读入内存中

将JSON文件读入内存中,第1张

将JSON文件读入内存中

目录
  • 1 目的
  • 2 实现接口
  • 3 示例

1 目的

将本地的json文件中的内容,读入内存中。

2 实现接口
int ReadFile2String(const char* szFileName, std::string& strFileContext)
{
    int iRet = 0;
    do
    {
        if( NULL == szFileName )
        {
            iRet = 1;
            break;
        }
        FILE * pTFile = fopen(szFileName, "rb");
        if( NULL != pTFile)
        {
            fseek(pTFile, 0, SEEK_END);
            int nFileSize = ftell(pTFile);
            if (-1 != nFileSize)
            {
                fseek(pTFile, 0, SEEK_SET);

                strFileContext.resize(nFileSize);
                char* pData = (char*)strFileContext.data();
                unsigned int nReadLen = 0;
                nReadLen = fread(pData, nFileSize, 1, pTFile);
                if (nReadLen != (unsigned int)nFileSize)
                {
                    ;
                }
            }
            fclose(pTFile);
            pTFile = NULL;
            break;
        }
        else
        {
            iRet = -1;
            break;
        }
    }while(0);
    return 0;
}

调用该接口:

3 示例

第一步:下载demo,点击链接下载;
第二步:将demo解压,里面的文件如下,把里面的文件夹拷贝到linux系统上;

第三步:编译并执行。

g++ readjson.cpp -o readjson
./readjson

结果:

"taskinfo":{"hello world !!!"}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5698695.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存