Binary file reading problem

Posted by ScReYm0 on Stack Overflow See other posts from Stack Overflow or by ScReYm0
Published on 2010-05-16T23:32:37Z Indexed on 2010/05/16 23:40 UTC
Read the original article Hit count: 278

Filed under:
|
|
|
|

Ok i have problem with my code for reading binary file...

First i will show you my writing code:

void book_saving(char *file_name, struct BOOK *current)
{
      FILE *out;
   BOOK buf;


      out = fopen(file_name, "wb");

   if(out != NULL)
   {
    printf_s("Writting to file...");
    do
    {
     if(current != NULL)
     {
      strcpy(buf.catalog_number, current->catalog_number);
      strcpy(buf.author, current->author);
      buf.price = current->price;
      strcpy(buf.publisher, current->publisher);
      strcpy(buf.title, current->title);
      buf.price = current->year_published;
      fwrite(&buf, sizeof(BOOK), 1, out);
     }
     current = current->next;
    }while(current != NULL);


    printf_s("Done!\n");
    fclose(out);
   }

}

and here is my "version" for reading it back:

int book_open(struct BOOK *current, char *file_name)
{
 FILE *in;
 BOOK buf;
 BOOK *vnext;
 int count;
 int i;

 in = fopen("west", "rb");
 printf_s("Reading database from %s...", file_name);
 if(!in)
 {
  printf_s("\nERROR!");
  return 1;
 }

 i = fread(&buf,sizeof(BOOK), 1, in);
 while(!feof(in))
 {

  if(current != NULL)
  {
   current = malloc(sizeof(BOOK));
   current->next = NULL;
  }

   strcpy(current->catalog_number, buf.catalog_number);
   strcpy(current->title, buf.title);
   strcpy(current->publisher, buf.publisher);
   current->price = buf.price;
   current->year_published = buf.year_published;
   fread(&buf, 1, sizeof(BOOK), in);

   while(current->next != NULL)
    current = current->next;

   fclose(in);

 }

 printf_s("Done!");

 return 0;




}

I just need to save my linked list in binary file and to be able to read it back ... please help me. The program just don't read it or its crash every time different situation ...

© Stack Overflow or respective owner

Related posts about binary

Related posts about files