So here's the code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "printFriends.h"
void main(int argc, char **argv)
{
int i,x,size,wordnum,friends;
char max[256],buffer[256];
char *fname,*prev,*curr;
FILE *file;
friend *friendArray;
//Check for command line arguments
if (argc <= 1)
{
printf("Insufficient number of inputs\n");
exit(1);
}
//Open the file and check if file exists
fname = argv[1];
file = fopen(fname,"r");
if (file == NULL)
{
printf("Cannot open input file %s\n",fname);
exit(2);
}
//Read in file line by line and search word
while(!feof(file))
{
fgets(max, sizeof(max), file);
prev = strtok(max," ");
while((curr = strtok(NULL," ")) != NULL)
{
if (strstr(curr, "circle") != NULL)
{
printf("%s %s",prev,curr);
//Skip lines amounting to number of circles
for(i=1;i<=atoi(prev);i++)
printf("\n");
}
if (strstr(curr, "friend") != NULL)
{
//Allocate array with the number of friends
friendArray = (friend *)malloc(sizeof(friend)*atoi(prev)+1);
friends = atoi(prev);
printf("%s %s",prev,curr);
//Insert items into array using for loop
for(x=0;x<friends;x++)
{
fgets(buffer,256,file);
friendArray[x].firstname = strtok(buffer," ");
friendArray[x].lastname = strtok(NULL," ");
strcpy(friendArray[x].birthdate,strtok(NULL," "));
}
defaultPrint(friendArray,friends,stdout);
}
}
}
fclose(file);
}
Here's the struct
Code:
#include <stdio.h>
#include <stdlib.h>
#include "printFriends.h"
void defaultPrint(friend *array, int num_friends, FILE *outfile)
{
int i;
printf("Default print function\n");
for(i=0;i<num_friends;i++)
fprintf(stdout,"%d: %s, %s, %s\n",i,
array[i].lastname,
array[i].firstname,
array[i].birthdate);
}
The output I get is
0: ri, Kasturi, 03031983
1: ri, Kasturi, 07011975
2: , Kasturi, 08251983
3: ri, Kasturi, 01012001
4: Hansen, Kasturi, 10051950
The output I want is
Zhang, Jane 03031983
Hernandez, John 07011975
Smith, Wenyue 08251983
Wassal, Jose 01012001
Hansen, Kasturi 10051950
My code just seems to take the last name on the list which is weird and I don't understand why.