c - 尝试读取 json 文件时出现段错误

标签 c json linux ubuntu jsmn

我正在尝试使用 jsmn 解析 json 文件,但在运行我的应用程序时出现段错误。我正在使用 C 并在 Ubuntu 机器上编译。

请在下面找到代码片段:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "jsmn.h"

#define JSON_FILE_PATH "/home/admin/Desktop/test/server/dataFile.json"
#define BUFFER_SIZE 5000
#define MAX_TOKEN_COUNT 128

// Read files
void readfile(char* filepath, char* fileContent)
{
    FILE *f;
    char c;
    int index;
    f = fopen(filepath, "r");
    ***while((c = fgetc(f)) != EOF){***     ------> seg fault
        fileContent[index] = c;
        index++;
    }
    fileContent[index] = '\0';
}

// This is where the magic happens
int parseJSON(char *filepath, void callback(char *, char*)){

    char JSON_STRING[BUFFER_SIZE];

    char value[1024];
    char key[1024];

    readfile(filepath, JSON_STRING);

   int i;
   int r;

   jsmn_parser p;
   jsmntok_t t[MAX_TOKEN_COUNT];

   jsmn_init(&p);

   r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/(sizeof(t[0])));

   if (r < 0) {
       printf("Failed to parse JSON: %d\n", r);
       return 1;
   }

   /* Assume the top-level element is an object */
   if (r < 1 || t[0].type != JSMN_OBJECT) {
       printf("Object expected\n");
       return 1;
   }

   for (i = 1; i < r; i++){

       jsmntok_t json_value = t[i+1];
       jsmntok_t json_key = t[i];


       int string_length = json_value.end - json_value.start;
       int key_length = json_key.end - json_key.start;

       int idx;

       for (idx = 0; idx < string_length; idx++){
           value[idx] = JSON_STRING[json_value.start + idx ];
       }

       for (idx = 0; idx < key_length; idx++){
           key[idx] = JSON_STRING[json_key.start + idx];
       }

       value[string_length] = '\0';
       key[key_length] = '\0';

       callback(key, value);

       i++;
   }

   return 0;
}

// Only prints the key and value
void mycallback(char *key, char* value){
    printf("%s : %s\n", key, value);
}

int main()
{
    parseJSON(JSON_FILE_PATH, mycallback);
    return 0;
}

当读取文件操作完成时,我在指示的行后出现段错误。

在调试时,此时 f 包含 0x00 值,这意味着它无法识别文件。

当文件存在于该位置时为什么会发生这种情况?

我试过改变路径,但还是一样的问题。

最佳答案

找到解决方案:

索引在使用前没有初始化 char c 应该是 int c - fgetc 返回一个 int

关于c - 尝试读取 json 文件时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53256169/

相关文章:

javascript - 此 package.json 文件需要更改哪些内容才能使用 npm 0.3.0?

c++ - 错误 'map' 未在此范围内声明

linux - 域作为 apache 中子域的后备

regex - awk,字段不匹配但应该匹配

c - 添加到 from 目录的链表数组

c++ - sqlite3程序收到信号SIGSEGV,sqlite3_get_table()中出现段错误

c - 如何在c中将用户给定的输入(字符串)与ubuntu中的/etc/passwd文件进行比较

c++ - 访问堆中的数据比访问栈中的数据快吗?

c# - 强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或 bool 值

java - 将java中的json字符串与javax.json进行配对