Code:
#define DEBUG 1
#include <stdio.h>
#include <stdlib.h>
#include <al/etl.h>
#include <sfl.h>
struct sb
{
int id;
int year;
int count;
char title[NAME_MAX];
char author[NAME_MAX];
float price;
struct sb* next;
};
/* BOOK MANAGEMENT */
typedef struct
{
struct sb* begin;
struct sb* now;
int count;
} BManager;
/* Function prototypes. */
void loadData( BManager *bmanager, char *booksFile );
void displayBooks( BManager *bmanager );
void getBookAttribute( char *delimiter, char *ZtoWhere, int *NtoWhere, float *FtoWhere );
/* MAIN!!! */
int main( int argc, char *argv[] )
{
/* VARs */
BManager bmanager;
/* Validate arguments */
ASSERT( argc == 2 );
/* Load the books from text data source */
loadData( &bmanager, *++argv );
/* Display the books */
displayBooks( &bmanager );
/* EXIT Success! */
return EXIT_SUCCESS;
}
/* Get book attribute from book line */
void getBookAttribute( char *delimiter, char *ZtoWhere, int *NtoWhere, float *FtoWhere )
{
char *ptr;
ASSERT( ( ptr = strtok( NULL, delimiter ) ) );
if( NtoWhere )
{
*NtoWhere = atoi( ptr );
printf( "Found: %d\n", *NtoWhere );
}
else if( FtoWhere )
{
*FtoWhere = atof( ptr );
printf( "Found: %f\n", *FtoWhere );
}
else if( ZtoWhere )
{
strncpy( ZtoWhere, ptr, NAME_MAX );
printf( "Found: %s\n", ZtoWhere );
}
}
/* Load all of the books from the bookList */
void loadData(BManager *bmanager, char *booksFile)
{
/* VARs */
char *delimiter = ":", *ptr;
char bookLine[LINE_MAX];
Bool firstBook = TRUE;
struct sb *b;
FILE *bfile;
/* fopen opens the file; exits if file cannot be opened */
ASSERT( ( bfile = fopen( booksFile, "r" ) ) );
/* Read from bfile */
while( fgets( bookLine, LINE_MAX, bfile ) )
{
/* Create some room for a book */
ASSERT( ( b = malloc( sizeof( struct sb ) ) ) );
/* Break down the bookline into attributes */
ASSERT( ( ptr = strtok( bookLine, delimiter ) ) );
b->id = atoi( ptr );
getBookAttribute( delimiter, b->title, NULL, NULL );
getBookAttribute( delimiter, b->author, NULL, NULL );
getBookAttribute( delimiter, NULL, &( b->year ), NULL );
getBookAttribute( delimiter, NULL, NULL, &( b->price ) );
getBookAttribute( delimiter, NULL, &( b->count ), NULL );
/* Put the book into the bookManager */
if( firstBook )
{
firstBook = FALSE;
bmanager->now = b;
bmanager->begin = b;
}
else
{
bmanager->now->next = b;
bmanager->now = bmanager->now->next;
}
bmanager->now->next = NULL;
bmanager->count++;
}
/* Destroy the file pointer */
fclose( bfile );
bfile = NULL;
}
void displayBooks( BManager* bmanager )
{
struct sb *aBook;
printf( "%2s %20s %16s %6s %6s %4s\n",
"ID",
"Title",
"Author",
"Year",
"Price",
"Count"
);
printf( "-----------------------------------------------------------\n");
bmanager->now = bmanager->begin;
while( bmanager->now )
{
printf( "%2d %20s %16s %6d $%5.2f %4d\n",
bmanager->now->id,
bmanager->now->title,
bmanager->now->author,
bmanager->now->year,
bmanager->now->price,
bmanager->now->count );
aBook = bmanager->now;
bmanager->now = bmanager->now->next;
free( aBook );
}
}