The following Code opens a given file and reads the names and puts them in a list.
What you want is a list of lists, something like an array of lists. Think of it and i will help you get the final answer to your problems.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct _Node
{
char *name;
struct _Node *next;
}Node;
typedef struct _List
{
int ListSize;
Node *head;
Node *tail;
}List;
Node *CreateNode(char *name)
{
Node *n = (Node *)calloc(1, sizeof(Node));
if(n)
{
n->name = strdup(name);
n->next = NULL;
return n;
}
else
return NULL;
}
List *CreateList()
{
List *l = (List *)calloc(1, sizeof(List));
if(l)
{
l->ListSize = 0;
l->head = NULL;
l->tail = NULL;
return l;
}
else
return NULL;
}
int ListInsertAtEnd(List *l, char *name)
{
if(l)
{
Node *n = CreateNode(name);
if(n)
{
if(!l->head && !l->tail)
{
l->head = n;
l->tail = n;
}
else
{
l->tail->next = n;
l->tail = n;
}
//Advance the list size.
l->ListSize++;
//Return the Value.
return 0;
}
else
{
printf("Memory Error.\n");
return -1;
}
}
else
{
printf("List is NULL.\n");
return -2;
}
}
void DumpList(List *l)
{
Node *n = NULL;
printf("List has size %d\n", l->ListSize);
for(n = l->head; n != NULL; n = n->next)
printf("%s ", n->name);
printf("\n");
}
void DeleteList(List *l)
{
Node *p = NULL;
Node *n = l->head;
while(n)
{
p = n->next;
free(n->name);
free(n);
n = p;
}
free(l);
l = NULL;
}
List *CreateListFromFile(char *filename)
{
FILE *file = NULL;
if(!filename)
{
printf("Enter a valid filename.\n");
return NULL;
}
else
{
List *l = CreateList();
if(!l)
{
printf("Error in Creating an Empty list.\n");
return NULL;
}
else
{
if(!(file = fopen(filename, "r")))
{
printf("Error can not open %s file.\n", filename);
DeleteList(l);
return NULL;
}
else
{
char *buffer = (char *)calloc(BUFSIZ, sizeof(char));
if(!buffer)
{
printf("Can not create Buffer.\n");
DeleteList(l);
return NULL;
}
else
{
char *token = NULL;
while(fgets(buffer, BUFSIZ, file) != NULL)
{
if(buffer[0] == '\0')
break;
if(buffer[strlen(buffer) -1] == '\n')
buffer[strlen(buffer) -1] = '\0';
token = strtok(buffer, " ");
if(token)
{
ListInsertAtEnd(l, token);
while(token)
{
token = strtok(NULL, " ");
if(token)
ListInsertAtEnd(l, token);
}
}
memset(buffer, 0 , BUFSIZ);
}
if(feof(file))
{
fclose(file);
free(buffer);
return l;
}
else
{
printf("Earlier break, the file is not read till the end.\n");
fclose(file);
free(buffer);
DeleteList(l);
return NULL;
}
}
}
}
}
}
int main(int argc, char **argv)
{
List *l = CreateListFromFile("test.txt");
DumpList(l);
return 0;
}
The code was writen in Visual Studio 2005, of course i suppose there are bugs..
Printed results using file "test.txt"
List has size 5
kostas nikos ilias baggelis giannis
Press any key to continue . . .
The names are in greek, can change them to anything, use a file named test.txt in your project directory and give names.
e.g "test.txt"
kostas niikos ilias baggelis giannis\n