Thread: Need abit help about link list and structure..thanks

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    36

    Need abit help about link list and structure..thanks

    i got another question let say i want to load my data from the database..i got stuck on the link list part..below this is only a sketch code..can give some advise..thanks a lot
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <string.h>
    
    
    /* Constants. */
    #define TITLE_LEN 40
    #define AUTHOR_LEN 15
    #define REPORT_FILE report.txt
    #define RESTOCK_LEVEL 5
    
    typedef struct saleStruct
    {
       struct tm date;
       int quantity;
       float price;
       struct saleStruct* next;
    } SaleType;
    
    typedef struct bookStruct
    {
       int id;
       char title[TITLE_LEN + 1];
       char author[AUTHOR_LEN + 1];
       int year;
       float price;
       int count;
       SaleType* head;
       struct bookStruct* next;
    } BookType;
    
    typedef struct bookListStruct
    {
       BookType* head;
       int count;
    } BookListType;
    
     BookType *head = NULL, *current, *previous;
     BookType booktype;
     
     typedef struct bookStruct booksT;
    /* Function prototypes. */
    void systemInit(BookListType*);
    void loadData(BookListType*, char*, char*);
    void displayBooks(BookListType*);
    void findBooks(BookListType*);
    void addBook(BookListType*);
    
    
    int main(void)
    {
       BookListType booklist;
       
       
    
    
    
       return EXIT_SUCCESS;
    }
    
    Code:
    /* part where i stuck...i want to add into link list */
    
    void loadData(BookListType* booklist, char* booksFile, char* salesFile)
    {
       
         FILE *bfile;
         FILE *sfile;
         booksFile = "books.dat";
         salesFile = "sales.dat";
         booklist = NULL;
         
    	/* fopen opens the file; exits if file cannot be opened */
    	if ( !( bfile = fopen( booksFile, "r" ) ) ) 
    	{
    		printf( "File %s could not be opened.\n", booksFile);
    		exit(100);
    	} 
    	
    	while(!feof(bfile))
    	{
    		booklist = malloc(sizeof(BookType));  /* allocate memory to current */
            
    		/*	copy the data from myBook to linked list 
    		 strcpy( current-> id , id );  /* error without casting */
    		strcpy( current -> title, title);
    		strcpy( current -> author, author);
    		strcpy( current -> year, year );  /* error without casting */
    		strcpy( current -> price, price );  /* error without casting */
    		strcpy( current -> count, price );  /* error without casting */
               */
    	}
    	fclose(fptr);
            
            
    	
    }
    void readRestOfLine() { int c; /* Read until the end of the line or end-of-file. */ while ((c = fgetc(stdin)) != '\n' && c != EOF) ; /* Clear the error and end-of-file flags. */ clearerr(stdin); } /* Initialises the system to a safe empty state. */ void systemInit(BookListType* booklist) { if (booklist != NULL) booklist->count=0; }

  2. #2
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    In this function : loadData(BookListType* booklist, char* booksFile, char* salesFile)

    You open the file, but never read anything from it!!

    Also check up on why using feof() as the loop condition is not a good idea.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    1. Get some paper and a pencil.
    2. Draw lots of linked lists out
    Code:
    +----+    +----+    +----+    +----+    +----+
    |HEAD|--->|NODE|--->|NODE|--->|NODE|--->|NODE|--->NULL
    +----+    +----+    +----+    +----+    +----+
    3. Produce "storyboards" of how the list changes when you add/remove nodes from the list.

    Until you have a clear mental picture of how all those pointers work, any single error in your use of pointers makes the whole thing go wrong in the most spectacular fashion.

    4. Keep the linked list code really simple - don't for example mix data input and output with list manipulation.
    Use the work you did on paper to guide you in creating a small set of list primitives (create, add, remove etc) to do the detailed work.
    Code:
    SaleType *newSale ( void ) {
        SaleType *new = malloc ( sizeof *new );
        if ( new ) {
            new->next = NULL;
        }
        return new;
    }
    SaleType *listAppend ( SaleType *head, SaleType *newnode ) {
      // over to you.
    }
    Then your calling code would be something like
    Code:
    while ( something ) {
        node = newSale();
        node->member = value;
        list = listAppend ( list, node );
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    36
    Ok..Thanks for helping me..i appreciate it alot...

  5. #5
    Registered User
    Join Date
    Apr 2005
    Posts
    134
    Following is wrong,
    Code:
    strcpy( current-> id , id );  /* error without casting */
    strcpy( current -> year, year );  /* error without casting */
    strcpy( current -> price, price );  /* error without casting */
    strcpy( current -> count, price );  /* error without casting */
    id,year and count are of type integer and price is float. Use "=" to store values to in it. strcpy() is used to copy char array only.

    Also, you need to pass BookType and not BookList Type to loadData() function. If you want to store the count you can return it as a return value of the function.

    Code:
    booklist.count = loadData( /*Arguments */);
    Also, in load data you need to build the linked list of books. Just pass the head pointer to it.

    Use fgets() instead of feof() to read check the end-of-file.

    Code:
    int main()
    {
       BookType *head=NULL;
       BookListType booklist;
       const char *booksfile="abc.txt";
       const char *salesfile= "xyz.txt";
       
       booklist.count=loadData(&head, booksfile,salesfile);
       booklist.head=head;
       printf("Total Records loaded: %d\n",booklist.count);
       return 0;
    }
    
    int loadData(BookType **head,char *booksfile,char *salesfile)
    {
       int count=0;
       BookType *current=NULL;
       BookType *last=NULL;
       FILE *bp;  /*books file pointer */
       char line[200]; /*buffer to read from file*/
      
       bp = fopen(booksfile,"r");
       
      if (bp==NULL)
      {
         printf("Can not open booksfile %s\n",booksfile);
         return 0;
      } 
       
      while ((fgets(line,sizeof(line),bp)) !=NULL)
      {		
    		   
            if ((*head)==NULL)
            {
               /* Build First node */
               (*head)=(BookType *)malloc(sizeof(BookType));
               if ((*head) == NULL )
               {
                  printf("Malloc failed for (*head) pointer\n");
                  return 0;
               }
               sscanf(line,"%d  %s  %s  %d  %f  %d",
                                 &(*head)->id, (*head)->title, 
                                 (*head)->author,&(*head)->year,  
                                 &(*head)->price,&(*head)->count);
               (*head)->head = getSalesInfo((*head)->title); /*get book sales detail based on title*/ 
               (*head)->next=NULL;
               last=(*head);
               count++;
    	} else {
               /*Build remaining nodes */
               current=(BookType *)malloc(sizeof(BookType));
               if (current == NULL )
               {
                  printf("Malloc failed for current pointer\n");
                  return 0;
               }
               sscanf(line,"%d  %s  %s  %d  %f  %d",
                         &((current)->id), current->title,   
                         current->author,&((current)->year),
                         &((current)->price),&((current)->count));
                current->head = getSalesInfo(current->title); /*get book sales detail based on title*/ 
               current->next=NULL;
               last->next=current;
               last=current;
               count++;
            }
            
      }
       
       return count;
    }
    Also, dont forget to free the memory that you are mallocing.

    Write a function to free the linked list, pass the head pointer to it. Just walk through the list and free individual nodes.
    Last edited by nkhambal; 05-08-2005 at 12:18 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM