#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define IN_FILE "Test.txt"
#define BUF_SIZE 1024
#define ITEM_UNIT 32
int main()
{
char **Items = NULL;
int NumItem = 0, SizeItem = 0, i;
char buf[BUF_SIZE];
FILE *iFP;
srand((unsigned int)time(NULL));
rand();
iFP = fopen(IN_FILE, "rt");
if(!iFP)
{
perror(IN_FILE);
exit(1);
}
while(fgets(buf, sizeof(buf), iFP))
{
char *temp = strchr(buf, '\n');
if(temp)
*temp = '\0';
temp = strtok(buf, ",");
while(temp)
{
if(*temp != '\0')
{
if(NumItem >= SizeItem)
{
Items = (char **)realloc(Items, SizeItem += ITEM_UNIT);
if(!Items)
{
perror("Items Buffer") ;
exit(2);
}
}
temp = strdup(temp);
if(!temp)
{
perror("Item Duplicate");
exit(3);
}
Items[NumItem++] = temp;
}
temp = strtok(NULL, ",");
}
}
fclose(iFP);
if(!NumItem)
{
perror("No Item");
exit(4);
}
// for(i = 0; i < NumItem; ++i)
// printf("%d=%s\n", i, Items[i]);
// putchar('\n');
i = (int)(rand() / (double)(RAND_MAX + 1) * (double)NumItem);
// printf("%d=", i);
puts(Items[i]);
return 0;
}