This is a simple string list library I made in C. It shows how to use a struct, a dynamically sized pointer array and some file loading.
list.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#ifndef LIST_H #define LIST_H typedef struct { int capacity; int size; int index; char **items; } simple_list; simple_list *list_create(int capacity); int list_add(simple_list* list, char *item); char *list_item(simple_list* list, int index); char *list_getnext(simple_list* list); char *list_loop(simple_list* list); int list_load_file(simple_list* list, char *name); void list_free(simple_list *list); #endif |
list.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
#include <string.h> #include <stdio.h> #include <stdlib.h> #include "list.h" simple_list *list_create(int capacity) { if(capacity <= 0) capacity = 100; simple_list *list = (simple_list *)malloc(sizeof(simple_list) * capacity); if(list != NULL) { list->capacity = capacity; list->size = 0; list->index = 0; list->items = malloc(capacity * sizeof(char *)); } return list; } int list_add(simple_list* list, char *item) { if((list->size + 1) > list->capacity) { // double the capacity. size_t newCapacity = (list->capacity * 2) * sizeof(char *); printf("resizing list to %d\n", newCapacity); // resizes the array and preserves the data. list->items = (char **) realloc(list->items, newCapacity); list->capacity = newCapacity; } int itemSize = strlen(item); char *newItem = NULL; if((newItem = (char *)malloc(itemSize * sizeof(char))) != NULL) { strcpy(newItem, item); list->items[list->size++] = newItem; return 1; } return -1; } char *list_item(simple_list* list, int index) { if(index > list->size) return NULL; return list->items[index]; } char *list_getnext(simple_list* list) { if(list->index + 1 > list->size) return NULL; return list->items[list->index++]; } char *list_loop(simple_list* list) { if(list->index + 1 > list->size) list->index = 0; else list->index++; return list->items[list->index]; } int list_load_file(simple_list* list, char *name) { char buff[1024]; FILE *fp = fopen(name, "r"); if( fp != NULL ){ while (!feof(fp)) { memset(buff, '\0', sizeof( buff) ); fgets(buff, 1024, (FILE*)fp); list_add(list, buff); } printf("list loaded size=%d, capacity=%d\n", list->size, list->capacity); fclose(fp); } else { printf("error loading list (%s)\n", name); } return list->size; } void list_free(simple_list *list) { int i = 0; for(i = 0; i < list->size; i++) { free(list->items[i]); } free(list); } |