Thread: writing to a binary file

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    4

    writing to a binary file

    Im writing to a Binary file. Having real difficulty. Not sure if I'm on the right track. Here is my code.

    Code:
    // Project 2.c : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    #include <stdio.h>
    
    #include <stdlib.h>
    
    #include <conio.h>
    
     
    
    // ------------------- New types declared - Global types.-------------------
    
    struct addr
    
    {
    
          char first_name[30];
    
          char surname[40];
    
          char address1[40];
    
          char county[50];
    
          char country[30];
    
          int  sex;              // 1 for female, 0 for male
    
          int  active_member;
    
          int  member_num;
    
          int  end;          // 1 for yes, 0 for no
    
    };
    
     
    
    //------------------ Global Variables -------------------------
    
    FILE *fp;
    
     
    
    // ----------------- Function prototypes ----------------------
    
     
    
    int main(void);
    
    void details(struct addr *, int); // Using pass by reference for structure.
    
    void display_details(struct addr); // Display details on screen
    
    void store_details(struct addr);  // Stores structure to disk
    
    void retrieve_details(struct addr *, int);
    
     
    
    // ------------------------------------------------------------
    
     
    
    int main(void)
    
    {
    
          struct addr member_details[100];                // Declare variable to use.
    
          struct addr disk_details;
    
          int i;
    
     
    
        // Open file for writing - create file or blank it.
    
    	  if((fp = fopen("store.bin","wb")) == NULL)
    
          {
    
                printf("Cannot open file \"store.bin\" for writing.....\n");
    
                exit(1);
    
          }
    
     
    
          for (i = 0; i <= 100; i++)      // Limited to 100 members for the time being.
    
          {
    
                details(&member_details[i], i);   // Function call
    
                store_details(member_details[i]);
    
          }
    
         
    
          for (i=0; i<=100; i++)
    
          {
    
                printf("Member number %d details:\n", i+1);
    
                retrieve_details(&disk_details, i);
    
                display_details(member_details[i]);
    
          }
    
     
    
         
    
    fclose(fp);
    
    }
    
     
    
    /* -----------------------------------------------------------------
    
          Function to get and store the details of each member.
    
          Called:      details(struct addr *);
    
          IN:         struct addr *: Address  of structure addr to store details in.
    
                      int : member number;
    
          OUT:      Filled structure.
    
     ---------------------------------------------------------------- */
    
     
    
    void details(struct addr *member, int i)
    
    {
    
          //int i;
    
          printf("Enter first name for member %d: ", i);
    
          scanf("%s", member->first_name);
    
     
    
          printf("Enter surname for member %d: ", i);
    
          scanf("%s", member->surname);
    
     
    
          printf("Enter the first line of address for member %d: ", i);
    
          scanf("%s", member->address1);
    
               
    
          printf("Enter county for member %d: ", i);
    
          scanf("%s", member->county);
    
                     
    
          printf("Enter country for member %d: ", i);
    
          scanf("%s", member->country);
    
                     
    
          printf("Is member %d active (1=Y/0=N): ", i);
    
          scanf("%d", &member->active_member);
    
               
    
          printf("Is member %d male or female (1=Y/0=N): ", i);
    
          scanf("%d", &member->sex);
    
     
    
          printf("End\? (1=Y/0=N); ");
    
          scanf("%d",&member->end);
    
          member->member_num = i;
    
     
    
          printf("\n\n");
    
    }
    
     
    
    void display_details(struct addr member)
    
    {
    
          printf("\tFirst name = %s\n", member.first_name);
    
          printf("\tSurname = %s\n", member.surname);
    
          printf("\tAddress line 1 = %s\n", member.address1);
    
          printf("\tCounty = %s\n", member.county);
    
          printf("\tCountry = %s\n", member.country);
    
          printf("\n\n");
    
     
    
    }
    
     
    
     
    
    void store_details(struct addr member)
    
    {
    
          fseek(fp, 0, SEEK_END);
    
                // Write structure to file.
    
     
    
         
    
          fwrite(&member, sizeof(struct addr), 1, fp);
    
    }
    
     
    
     
    
    void retrieve_details(struct addr *member, int num)
    
     
    
    {
    
          fseek(fp, (num * sizeof(struct addr)), SEEK_SET);
    
     
    
          fread(member, sizeof(struct addr), 1, fp);
    
     
    
    }

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    for (i=0; i<=100; i++)

    goes from 0-100, meaning 101 elements.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Good thing to do - is to check return values of all functions that can fail. That includes not only fopen, but also
    fread, printf, scanf etc
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    printf()? Okkaaaaay. I usually only check the return value of printf() if I want to know how many characters it wrote -- for example, to line up columns or whatever. In common practice, I don't think this gets checked very often.

    Anyway. Don't double-space all of your code. It just makes it hard to read, because you have to move your eyes and scroll really far. (Unless it was caused by a line ending translation thing . . . .)

    As Elysia would say -- you shouldn't read strings with scanf("&#37;s"). I mean, you can, but strings with spaces are going to be broken up. Consider scanf("%[^\n80]") (I think that's right) or fgets() instead.

    Passing such a large structure as struct addr around by value, as you do for display_details(), might not be the best idea. If you're worried about the contents of the structure getting
    changed, you can always use const pointers.

    Code:
    printf("Cannot open file \"store.bin\" for writing.....\n");
    Consider perror(). It could tell you what went wrong.

    Code:
    int main(void);
    Prototyping main() -- whew! Haven't seen that in a while. Unless you're using an extremely ancient unconforming compiler (or an embedded one, which is very unlikely), you don't need to do this. Or unless you're recursively calling main(), which you aren't and probably shouldn't, because it's disallowed in C++. They must have had their reasons.

    You probably don't need the member addr::end. You can use EOF for that.

    Another thing -- don't including <conio.h>. It's non-standard, and (thankfully) you're not using anything from it. Things like getch(), getche(), kbhit(), clrscr(), etc are in this header file. Please, don't use them if you can help it.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Code:
    >            retrieve_details(&disk_details, i);
    >            display_details(member_details[i]);
    You read the data into disk_details, but then print a different variable, the array member_details.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Replies: 2
    Last Post: 05-09-2008, 07:27 AM
  3. Replies: 1
    Last Post: 12-10-2005, 11:25 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM