我正在使用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/