tor_multipath_voip/src/tor_os.c
2019-02-08 17:37:02 +01:00

75 lines
1.7 KiB
C

#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++;
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;
int n = 0;
while (1) {
char* dst = tor_os_append_cursor(os);
if (dst == NULL) break;
if (getline(&(os->list[n]),&len,fd) == -1) break;
}
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);
target = malloc(sizeof(char*) * (strlen(entry) + 1));
if (target == NULL) return -1;
strcpy (target, entry);
return 0;
}