Working read_config_file function
This commit is contained in:
parent
b0d75ae57c
commit
af4051dfbe
18
main.c
18
main.c
@ -91,7 +91,6 @@ void showHosts()
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Read the configuration file and give a return code to indicate any changes.
|
* Read the configuration file and give a return code to indicate any changes.
|
||||||
* TODO: overwrites hosts, but doesn't handle if the list shrinks.
|
|
||||||
* @return 1 if successful, 0 if otherwise.
|
* @return 1 if successful, 0 if otherwise.
|
||||||
*/
|
*/
|
||||||
int read_config_file() {
|
int read_config_file() {
|
||||||
@ -103,6 +102,8 @@ int read_config_file() {
|
|||||||
|
|
||||||
if (config == NULL) {
|
if (config == NULL) {
|
||||||
fprintf(stderr, "Error trying to open config file: %s\n", strerror(errno));
|
fprintf(stderr, "Error trying to open config file: %s\n", strerror(errno));
|
||||||
|
fclose(config);
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// Add each line from the file to the linked list.
|
// Add each line from the file to the linked list.
|
||||||
@ -110,24 +111,27 @@ int read_config_file() {
|
|||||||
|
|
||||||
buf[strlen(buf) - 1] = 0;
|
buf[strlen(buf) - 1] = 0;
|
||||||
|
|
||||||
// We should add a method that overwrites the linked list node at an index.
|
|
||||||
fprintf(stderr, "Read %s from config file\n", buf);
|
|
||||||
|
|
||||||
// overwrite data in these nodes.
|
// overwrite data in these nodes.
|
||||||
if (ptr != NULL && strcmp(buf, ptr->data) != 0) {
|
if (ptr != NULL) {
|
||||||
if (strlen(ptr->data) < strlen(buf)) {
|
if (strlen(ptr->data) < strlen(buf)) {
|
||||||
if ((ptr->data = realloc(ptr->data, strlen(buf))) == NULL) {
|
if ((ptr->data = realloc(ptr->data, strlen(buf))) == NULL) {
|
||||||
fprintf(stderr, "Failed to realloc pointer\n");
|
fprintf(stderr, "Failed to realloc pointer\n");
|
||||||
exit(1);
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
strcpy(ptr->data, buf);
|
strcpy(ptr->data, buf);
|
||||||
|
prev = ptr;
|
||||||
ptr = ptr->next;
|
ptr = ptr->next;
|
||||||
} else {
|
} else {
|
||||||
linkedlist_add(&hosts, buf);
|
linkedlist_add(&hosts, buf);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// In this case, the list got chopped off, we need to reset pointers and free the rest of our list.
|
||||||
|
if (ptr != NULL) {
|
||||||
|
prev->next = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
// If we didn't exhaust the linked list, then we need to free any remaining nodes because the list
|
// If we didn't exhaust the linked list, then we need to free any remaining nodes because the list
|
||||||
// shortened.
|
// shortened.
|
||||||
while (ptr != NULL) {
|
while (ptr != NULL) {
|
||||||
@ -136,6 +140,8 @@ int read_config_file() {
|
|||||||
free(prev->data);
|
free(prev->data);
|
||||||
free(prev);
|
free(prev);
|
||||||
}
|
}
|
||||||
|
fclose(config);
|
||||||
|
return 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user