Add more functions!
Learn to split bits of functionality into functions to stop your main bloating.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 50
typedef struct node {
char name[MAXN];
int age;
struct node *next;
} node;
typedef struct list {
node *head;
node *tail;
} list;
node *newNode() {
node *new = malloc(sizeof(*new));
if ( new ) {
new->next = NULL;
}
return new;
}
void appendToList(list *root, node *new) {
if ( root->head == NULL ) {
root->head = root->tail = new;
} else {
root->tail->next = new;
root->tail = new;
}
}
void parseLine(list *root, char inputbuff[] ) {
char name[MAXN];
int age;
if ( sscanf(inputbuff,"%s %d",name,&age) == 2 ) {
node *new = newNode();
if ( new ) {
strcpy(new->name,name);
new->age = age;
appendToList(root,new);
}
} else {
fprintf(stderr,"Unable to parse %s",inputbuff);
}
}
int main (int argc, char **argv) {
FILE *file = argc > 1 ? fopen (argv[1], "r") : stdin;
if (file == NULL)
return 1;
char buf[MAXN];
list myList = { NULL, NULL };
while (fgets (buf, MAXN, file)) {
parseLine(&myList,buf);
}
if (file != stdin)
fclose(file);
node *ptr = myList.head;
while (ptr != NULL) {
node *node_t = ptr;
printf ("%s is %d years old\n", ptr->name,ptr->age);
ptr = ptr->next;
free (node_t);
}
return 0;
}