#include "tor_os.h" void tor_os_create(struct tor_os_str* os, char* file, size_t size) { os->size = size; os->filled = 0; os->file = malloc(sizeof(char) * (strlen(file) + 1)); if (os->file == NULL) goto mem_error; strcpy(os->file, file); os->list = malloc(size * sizeof(char*)); if (os->list == NULL) goto mem_error; return; mem_error: fprintf(stderr, "unable to allocate memory\n"); exit(EXIT_FAILURE); } char** tor_os_append_cursor(struct tor_os_str* os) { if (os->filled == os->size) { return NULL; } char** cur = os->list + os->filled; os->filled++; *cur = NULL; return cur; } void tor_os_read (struct tor_os_str* os) { FILE* fd = NULL; fd = fopen(os->file, "r"); if (fd == NULL) { return; } size_t len = 0; size_t str_len = 0; int n = 0; while (1) { char** dst = tor_os_append_cursor(os); if (dst == NULL) break; if (getline(dst,&len,fd) == -1) break; str_len = strlen(*dst); if (str_len < 1) break; if ((*dst)[str_len - 1] == '\n') { (*dst)[str_len - 1] = '\0'; } } fclose(fd); } void tor_os_free(struct tor_os_str* os) { for (int i = 0; i < os->filled; i++) { free(os->list[i]); } free(os->list); free(os->file); } void tor_os_persist(struct tor_os_str* os) { FILE* fd = NULL; fd = fopen(os->file, "w"); if (fd == NULL) { fprintf(stderr, "unable to open file for writing\n"); exit(EXIT_FAILURE); } for (int i = 0; i < os->filled; i++) { fprintf(fd, "%s\n", os->list[i]); } fclose(fd); } int tor_os_append(struct tor_os_str* os, char* entry) { char** target = tor_os_append_cursor (os); if (target == NULL) return -1; *target = malloc(sizeof(char) * (strlen(entry) + 1)); if (*target == NULL) return -1; strcpy (*target, entry); return 0; }