
C Programming Assignment Solution on Linked List
- 29th Jul, 2022
- 15:19 PM
#include #include //for string manipulation #include #include #include "linked_list.h" #define BUFFER_SIZE 1024 void addToList(list_t* l, char* line) { if (l->head == NULL) { l->head = (node_t*)malloc(sizeof(node_t)); l->head->line = line; l->head->next = NULL; l->tail = l->head; } else { node_t* new_node = (node_t*)malloc(sizeof(node_t)); new_node->line = line; new_node->next = NULL; l->tail->next = new_node; l->tail = new_node; } } void printList(list_t* l) { int counter = 1; node_t* current = l->head; while(current != NULL) { printf("%03d: %s", counter, current->line); current = current->next; counter++; } } void freeList(list_t* l) { node_t* current = l->head; while(current != NULL) { node_t* node = current; current = current->next; free(node->line); free(node); } } int main (int argc, char *argv[]){ FILE *ifile = stdin; // inputfile, initit as stdin int i; char buf[BUFFER_SIZE] = {0}; // for no exceed more than BUFFER_SIZE length {0} = init everything with 0 char *file_name = NULL; char *buf_ptr = NULL; list_t list; list.head = NULL; list.tail = NULL; for(i = 1; i file_name = argv[i]; ifile = fopen(file_name, "r"); if(ifile == NULL){ perror("failed open file"); fprintf(stderr,"cannot file open : %s\n",file_name); exit(EXIT_FAILURE); } buf_ptr = fgets(buf, BUFFER_SIZE, ifile); while (buf_ptr != NULL){ int len = strlen(buf_ptr) + 1; char* line = (char *)malloc(len * sizeof(char)); strcpy(line, buf_ptr); addToList(&list, line); buf_ptr=fgets(buf, BUFFER_SIZE, ifile); } fclose(ifile); } printList(&list); freeList(&list); return(EXIT_SUCCESS); }