I am working on a simple function to take input from a file, and display the input on screen using fgets. The input file consists of names of birds. Each bird name has two words, such as "Cedar Waxwing". There is only one bird name per line. Apart from displaying the bird list on screen, I also want to break down the bird name into two tokens. So in this case token1 is Cedar, and token2 is Waxwing. My code compiles correctly but when I execute it I get a lot of garbage output, followed by several lines of "Cedar Waxwing", which is the first bird. None of the other bird names appear on screen. I dont know why this is happening. Any help will be appreciated. Thanks.
Code:
#define DELIMITERS " "
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *p;
char tokens[20][50];
int x=0;
int i;
unsigned char buffer[20];
FILE *fp;
fp = fopen("bird_names.txt","r");
i=0;
while(fgets(buffer, 20, fp)!=NULL){
p=strtok(buffer, DELIMITERS);
while (p!=NULL)
{
strcpy(tokens[i], p);
p=strtok(NULL, DELIMITERS);
printf("%s %s",tokens[0],tokens[1]);
i++;
}
}
return 0;
}