C – Simple List

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

#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

#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);
}