Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple progran to maintain inventory

Status
Not open for further replies.

new2C

Technical User
May 1, 2001
1
US
Hi,

Given the following can anyone complete it so that I can add books to an inventory. I am complete beginner and lost on where to go with it. From there I need to develop it to find, and modify books in the inventory. If I can just get the add part going I think I can do the rest. I am programming in C and using Unix to compile.

Thanks for any help!

#include <stdio.h>


FILE* datafile = fopen(&quot;books.dat&quot;, &quot;w&quot;);
if (datafile == NULL) {
/* ... could not create file ... */
}


typedef struct Book_ {
char title[40];
char author[40];
char publisher[50];
float cost;
int pages;
} Book;

 
I do not see what could be the problem here. You need to create a variable of type Book and initialize its fields, then append to the file contents.

Book NewBook;
NewBook.title = &quot;The Wheel of Time / Lord of Chaos&quot;;
NewBook.author = &quot;Robert Jordan&quot;;
NewBook.publisher = &quot;Tom Doherty Associates, Inc&quot;;
NewBook.cost = 19.95;
NewBook.pages = 716;

Then you write NewBook to the file. Best Regards,

aphrodita@mail.krovatka.ru {uiuc rules}
 
Except for you can't initalize the members of Book like that since they're arrays. You'll need strcpy().

/* Incomplete, untested and some error checking omitted */

#include <stdlib.h>
#include <string.h>

typedef struct Book_ {
char title[40];
char author[40];
char publisher[50];
float cost;
int pages;
} Book;

/* create a book */

Book *
createBook(const char *title,
const char *author,
const char *publisher,
float cost,
int pages)
{
Book *book=malloc(sizeof *book);
if (book!=NULL) {
strcpy(book->title,title);
strcpy(book->author,author);
strcpy(book->publisher,publisher);
book->cost=cost;
book->pages=pages;
}
return book;
}

/* destroy a book */
void
destroyBook(Book *book)
{
free(book);
}
/* write a book to a file */
int
writeBook(Book *book,const char *fname)
{
/* ... */
}
Book *newBook=createBook(&quot;Tons and Tons of Bees&quot;,
&quot;Spatula&quot;,
&quot;Spartacus&quot;,
9.95,
20000);

if (newBook!=NULL) {
if (writeBook(newBook,&quot;myfile.txt&quot;)!=0) {
/* error */
}
destroyBook(newBook);
}

If you need more help, post the code you're having trouble with.

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top