C 语言中的 CCAN JSON 序列化

标签 c json file

我正在使用JSON图书馆。它非常轻巧且易于理解,但我对 json_decode 有一个问题。我正在从文件中读取数据(JSON):

FILE *instream = fopen("/tmp/file.dat", "r");
char ch;
int count = 0;
do {
    ch = getc(instream);
    inbuffer[count] = ch;
count++;
} while (!feof(instream) && ch != '\0');

我的文件如下所示,因此 inbuffer 具有相同的文本

[
        {
                "MBV": 0,
                "CRRC": 0,
                "LFrei": 0
        }                
]

我尝试解码它以获取 JsonNode 变量

static char *chomp(char *s) //function taken from CCAN JSON example
{
    char *e;
    if (s == NULL || *s == 0)
        return s;

    e = strchr(s, 0);
    if (e[-1] == '\n')
        *--e = 0;
    return s;
}

const char *s = chomp(inbuffer);
JsonNode *jin = json_decode(s);
printf("JSON: %s\n", jin);

运行程序后,我得到

JSON: (null)

有人可以告诉我为什么 json_decode 函数不想读取 JSON 格式的文件,即使使用此库创建的文件也是如此?

最佳答案

我不知道您使用的 JSON 库,但我怀疑发生错误是因为 inbuffer 未正确以 NUL 终止。在文件末尾,getc() 返回 EOF (-1) 在 feof() 返回 TRUE 之前复制到 inbuffer 中的内容。我会这样做:

while( (ch = getc( instream )) != EOF ) {
   inbuffer[count] = ch;
   count++;
}
inbuffer[count] = '\0';

或者只使用fread():

count = fread( inbuffer, 1, sizeof( inbuffer ) - 1, stream );
inbuffer[count] = '\0';

关于C 语言中的 CCAN JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22045744/

相关文章:

c - Linux C : How to know the default interface for internet access?

c - 扫描包含多个单词的字符串

c++ - 无法在从 C++ 类继承的结构上调用正确的构造函数

java - 使用列表/表中的 json 创建树

json - PostgreSQL - 创建索引在更新完成之前运行

java - 使用android存储文件和文件夹

C:将多个区域读入数组并求最大值

javascript - 同步跨域AJAX请求

Java 文件复制 - 将同一文件并行复制到 10/20 USB 设备

python - 如何检查文件是否存在无异常?