tor_multipath_voip/src/tor_os.c

75 lines
1.7 KiB
C
Raw Normal View History

2019-02-08 13:28:39 +00:00
#include "tor_os.h"
2019-02-08 16:37:02 +00:00
void tor_os_create(struct tor_os_str* os, char* file, size_t size) {
2019-02-08 13:28:39 +00:00
os->size = size;
os->filled = 0;
2019-02-08 16:37:02 +00:00
os->file = malloc(sizeof(char*) * (strlen(file) + 1));
if (os->file == NULL) goto mem_error;
strcpy(os->file, file);
2019-02-08 13:28:39 +00:00
os->list = malloc(size * sizeof(char*));
2019-02-08 16:37:02 +00:00
if (os->list == NULL) goto mem_error;
return;
mem_error:
fprintf(stderr, "unable to allocate memory\n");
exit(EXIT_FAILURE);
2019-02-08 13:28:39 +00:00
}
2019-02-08 16:37:02 +00:00
char* tor_os_append_cursor(struct tor_os_str* os) {
2019-02-08 13:28:39 +00:00
if (os->filled == os->size) {
return NULL;
}
char* cur = os->list[os->filled];
os->filled++;
return cur;
}
2019-02-08 16:37:02 +00:00
void tor_os_read (struct tor_os_str* os) {
2019-02-08 13:28:39 +00:00
FILE* fd = NULL;
2019-02-08 16:37:02 +00:00
fd = fopen(os->file, "r");
2019-02-08 13:28:39 +00:00
if (fd == NULL) {
return;
}
size_t len = 0;
int n = 0;
while (1) {
2019-02-08 16:37:02 +00:00
char* dst = tor_os_append_cursor(os);
2019-02-08 13:28:39 +00:00
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);
2019-02-08 16:37:02 +00:00
free(os->file);
2019-02-08 13:28:39 +00:00
}
2019-02-08 16:37:02 +00:00
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;
}