iniwrite.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "iniparser.h"
  2. void create_empty_ini_file(void)
  3. {
  4. FILE *ini;
  5. if ((ini = fopen("example.ini", "w")) == NULL) {
  6. fprintf(stderr, "iniparser: cannot create example.ini\n");
  7. return;
  8. }
  9. fclose(ini);
  10. }
  11. int write_to_ini(const char *ini_name)
  12. {
  13. void *dictionary;
  14. FILE *ini_file;
  15. int ret = 0;
  16. if (!ini_name) {
  17. fprintf(stderr, "Invalid argurment\n");
  18. return -1;
  19. }
  20. dictionary = iniparser_load(ini_name);
  21. if (!dictionary) {
  22. fprintf(stderr, "cannot parse file: %s\n", ini_name);
  23. return -1;
  24. }
  25. /* set section */
  26. ret = iniparser_set(dictionary, "Pizza", NULL);
  27. if (ret < 0) {
  28. fprintf(stderr, "cannot set section in: %s\n", ini_name);
  29. ret = -1;
  30. goto free_dict;
  31. }
  32. /* set key/value pair */
  33. ret = iniparser_set(dictionary, "Pizza:Cheese", "TRUE");
  34. if (ret < 0) {
  35. fprintf(stderr, "cannot set key/value in: %s\n", ini_name);
  36. ret = -1;
  37. goto free_dict;
  38. }
  39. ini_file = fopen(ini_name, "w+");
  40. if (!ini_file) {
  41. fprintf(stderr, "iniparser: cannot create example.ini\n");
  42. ret = -1;
  43. goto free_dict;
  44. }
  45. iniparser_dump_ini(dictionary, ini_file);
  46. fclose(ini_file);
  47. free_dict:
  48. iniparser_freedict(dictionary);
  49. return ret;
  50. }
  51. int main(int argc, char *argv[])
  52. {
  53. int ret;
  54. if (argc < 2) {
  55. create_empty_ini_file();
  56. ret = write_to_ini("example.ini");
  57. } else
  58. ret = write_to_ini(argv[1]);
  59. return ret ;
  60. }