/* readstruct.c - This program is passed as command line parameter the 
	name of a text file. This file contains lines containing
	the following tokens	
		a name not longer than 30 characters
		an id not longer than 10 characters
		an integer
	These tokens may be separated by any number of white spaces,
	but the total length of a line must be at most 128.
	The program reads these lines and as it reads it prints out
	on separate lines the tokens. Tokens belonging to different lines 
	are separated by an empty line.
	At the end it prints out the sum of all the integers.
 */

#include <stdio.h>

#define MAXNAME 30
#define MAXID 10
#define MAXLINE 128

int main(int argc, char *argv[]) 
{
    /* Check that we have the right number of parameters */
    if (argc != 2) {
	printf("usage: %s filename\n", argv[0]);
	return 0;
    }

    /* Open the file */
    FILE *fin = fopen(argv[1], "r");
    if (fin == NULL) {
	printf("Unable to open %s\n", argv[1]);
	return 1;
    }

    /* Process the file */
    int total = 0;  /* the sum of all the integers read */
    char buffer[MAXLINE+1];
    while (fgets(buffer, MAXLINE, fin) != NULL) {
	char name[MAXNAME+1];
	char id[MAXID+1];
	int val;
	if (sscanf(buffer, "%s %s %d", name, id, &val) < 3) { 
	    printf("Wrong number of arguments in line: %s\n", buffer);
	} else {
	    total += val;
	    printf("\t%s\n\t%s\n\t%d\n\n", name, id, val);
	    /* Note that though we have said that name can have at most
	       MAXNAME characters and id MAXID characters, in our code
	       we are not making sure that that is the case. If we wanted 
	       to be sure we would have to write horrid code such as
               printf("\t%-*s\n\t%-*s\n\t%d\n\n", MAXNAME, name, MAXID, 
			id,val);
	    */
	}
    }

    /* Termination */
    printf("The total is: %d\n", total);
    fclose(fin);
    return 0;   
}
