This is my version, based on your original code:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct checkingnode
{
char num[8] ;
char comment[32] ;
char deb_cred[8] ;
float amt ;
char date[12] ;
float bal ;
struct checkingnode *nextptr ;
} ;
typedef struct checkingnode Checking ;
typedef Checking *checkptr ;
void check_open( checkptr * ) ;
int main(void)
{
checkptr firstptr = NULL, tmpptr;
check_open( &firstptr ) ;
tmpptr = firstptr;
// print the list to prove it worked.
while (tmpptr)
{
printf("%s %s %.2f\n", tmpptr->num, tmpptr->comment, tmpptr->amt);
tmpptr = tmpptr->nextptr;
}
// next job, write function to free all nodes in the list!
return (0);
}
/*****************************************
Function: check_open
Purpose: Opens the checking.dat file and
creates the checking linked list.
*****************************************/
void check_open( checkptr *sptr)
{
FILE *ptrReadDat ;
char buffer[200];
checkptr curptr = NULL, newptr;
Checking tmpNode;
if ((ptrReadDat = fopen( "checking.dat", "r" )) == NULL)
{
printf( "\nFile could not be opened.\n" ) ;
return;
}
while (fgets(buffer, 200, ptrReadDat)) // read a line
{
// sscanf is lame, 'cos it can't handle input errors.
// Also, strings are terminated when a white space character is read (eg space).
// Search the board for better ways of doing this type of thing.
if (sscanf( buffer, "%s\t%s\t%s\t%f\t%s\t%f\n", tmpNode.num, tmpNode.comment,
tmpNode.deb_cred, &tmpNode.amt, tmpNode.date, &tmpNode.bal ) == 6)
{ // line split up and stored into temp struct OK, so proceed
if ((newptr = malloc( sizeof( Checking ) )) == NULL)
{ // malloc up some memory
perror("out of memory");
fclose( ptrReadDat );
return; // do something better here
}
*newptr = tmpNode; // copy the tmp struct to the new memory
if (curptr == NULL)
{ // if first time...
curptr = newptr; // pointer to new memory
*sptr = curptr; // also update the calling pointer (from function arg)
}
else
{ // pointer already been used, so ...
curptr->nextptr = newptr; // make the link from one node to the next
curptr = newptr; // move the pointer to the next node
}
curptr->nextptr = NULL; // force the new nodes nextptr to NULL to prevent errors.
}
}
fclose(ptrReadDat);
}