You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

json_util.c 1.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include "bits.h"
  10. #include "debug.h"
  11. #include "printbuf.h"
  12. #include "json_object.h"
  13. #include "json_tokener.h"
  14. #include "json_util.h"
  15. struct json_object* json_object_from_file(char *filename)
  16. {
  17. struct printbuf *pb;
  18. struct json_object *obj;
  19. char buf[JSON_FILE_BUF_SIZE];
  20. int fd, ret;
  21. if((fd = open(filename, O_RDONLY)) < 0) {
  22. mc_error("json_object_from_file: error reading file %s: %s\n",
  23. filename, strerror(errno));
  24. return error_ptr(-1);
  25. }
  26. if(!(pb = printbuf_new())) {
  27. mc_error("json_object_from_file: printbuf_new failed\n");
  28. return error_ptr(-1);
  29. }
  30. while((ret = read(fd, buf, JSON_FILE_BUF_SIZE)) > 0) {
  31. printbuf_memappend(pb, buf, ret);
  32. }
  33. close(fd);
  34. if(ret < 0) {
  35. mc_abort("json_object_from_file: error reading file %s: %s\n",
  36. filename, strerror(errno));
  37. printbuf_free(pb);
  38. return error_ptr(-1);
  39. }
  40. obj = json_tokener_parse(pb->buf);
  41. printbuf_free(pb);
  42. return obj;
  43. }
  44. int json_object_to_file(char *filename, struct json_object *obj)
  45. {
  46. char *json_str;
  47. int fd, ret, wpos, wsize;
  48. if(!obj) {
  49. mc_error("json_object_to_file: object is null\n");
  50. return -1;
  51. }
  52. if((fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, 0644)) < 0) {
  53. mc_error("json_object_to_file: error opening file %s: %s\n",
  54. filename, strerror(errno));
  55. return -1;
  56. }
  57. if(!(json_str = json_object_to_json_string(obj))) return -1;
  58. wsize = strlen(json_str);
  59. wpos = 0;
  60. while(wpos < wsize) {
  61. if((ret = write(fd, json_str + wpos, wsize-wpos)) < 0) {
  62. close(fd);
  63. mc_error("json_object_to_file: error writing file %s: %s\n",
  64. filename, strerror(errno));
  65. return -1;
  66. }
  67. wpos += ret;
  68. }
  69. close(fd);
  70. return 0;
  71. }

No Description

Contributors (1)