This program is supposed to read in a text file and do the following:
- Read in the file
- Look for the line with the number of circles
- Skip the number of line there are of number of circles
- Look for line with number of friends
- Allocate an array with just enough space for the number of friends
- Parse and store the friends
Issues:
- I am not sure on how to parse the information into the friend array using the friend struct in defaultPrint.c
- Please look over my code if possible to mention any bugs or syntax I may have missed
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "printFriends.h"
void main(int argc, char **argv)
{
int i,x,size,wordnum;
char max[256];
char *fname,*word,*friends,*line,*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))
{
line = 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)
{
printf("%s %s",prev,curr);
//allocate array with the number of friends
friendArray = malloc(sizeof(friend)*atoi(prev)+1);
for(i=0;i<atoi(prev);i++)
{
//for loop maybe to store info into the friend
//struct/array???
}
}
}
}
//call defaultPrint somehow here
fclose(file);
}
defaultPrint.c
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);
}
printFriends.h
Code:
#ifndef PRINTFRIENDS_H
#define PRINTFRIENDS_H
typedef struct _friend{
char *lastname;
char *firstname;
char birthdate[9];
} friend;
void defaultPrint(friend *array, int num_friends, FILE *outfile);
#endif