how to dynamically create an array of structure and store the data in file.

This is a discussion on how to dynamically create an array of structure and store the data in file. within the C Programming forums, part of the General Programming Boards category; Hi everyone. I am writing a program for address book. There are insert, display and delete options. In insertion, it ...

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    23

    how to dynamically create an array of structure and store the data in file.

    Hi everyone.
    I am writing a program for address book. There are insert, display and delete options. In insertion, it takes input data and stores them to a file. whenever I add new contact it adds them to the file.
    After saving the data to file, Can i dynamically allocate an array of struct addressbook to store each contact details. So that if I want to display or delete a particular contact it will be easy other than opening a file, comparing each element in the file.
    Depending upon the number of contacts saved into the file, we have to dynamically allocate array for struct addressbook and store the details.

    Code:
    #define FIRST_NAME_LENGTH  15
    #define LAST_NAME_LENGTH   15
    #define NUMBER_LENGTH      15
    #define ADDRESS_LENGTH     15
    /* Structure defining a name */
    struct Name
    {
      char lastname[LAST_NAME_LENGTH];
      char firstname[FIRST_NAME_LENGTH];
    };
    
    /* Structure defining a phone record */
    struct addressbook 
    {
      char answer;
      struct Name name;
      char address[ADDRESS_LENGTH];
      char phonenumber[NUMBER_LENGTH];
      
    };
    struct addressbook a;
    void add_record()
    {
      printf("enter details\n");
      printf("enter lastname of person :\n");
      scanf("%s", a.name.lastname);
      printf("enter firstname of person :\n");
      scanf("%s", a.name.firstname);
      printf("enter address of person :\n");
      scanf("%s", a.address);
      printf("enter phone number of person :\n");
      scanf("%s", a.phonenumber);
    
      if((fp = fopen(filename,"a+")) == NULL){
        printf("Error opening %s for writing. Program terminated.\n", filename);
        abort();
      }
      fwrite(&a, sizeof(a), 1, fp);                  /* Write to the file */
    
    /* depending on the number of times we insert data to file, can we dynamically declare an array for stuct addressbook to store the file data. */
    
      fclose(fp);                                     /* close file */
      printf("New record added\n");
    }
    My original program is very long, so I posted the code for structure for addressbook and insert function in my program.
    Last edited by chaituchemico; 09-17-2011 at 06:59 PM.

  2. #2
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    See Lesson 15: Singly Linked Lists and File Operations. I would suggest using a binary file and setting up a Random Access File system
    Last edited by AndrewHunter; 09-17-2011 at 06:54 PM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  3. #3
    Registered User
    Join Date
    Sep 2011
    Posts
    23
    I edited my code. My original program is very long, so I posted only the main part of my program where I am having doubt. Thank you.

  4. #4
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    Yep! except for the very first time the address book is created. After that every time the program is run, it reads the file and stores it into an in-core linked list of nodes and it'd boost performance as memory is faster than disk.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,300
    What seems to be the problem?
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    First of all, linked lists are a massively silly way of building inventory programs (like an address book). You want a random access file system so you can go straight to the record you want, change it and replace it in place, without rewriting the entire file.

    Study the following code... look at how it accesses the disk file it creates... In particular notice that it only uses one struct for everything... you should be able to work with the same concepts in your own code...
    Code:
    //random access file demo
    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>
    #include <ctype.h>
    #include <string.h>
    
    #define FNAME "random.dat"
    
    // test data struct
    struct t_Record
      { int randnum;
        char word[16]; }
      Record;
    
    
    
    ///////////////////////////////////////////////////////
    // Random Access File Handlers
    //
    
    // open or create the file
    FILE *FileOpen(char* Filename)
      { FILE* pFile;
        pFile = fopen(Filename,"rb+");
        if (!pFile)
          pFile = fopen(Filename,"wb+");
        return pFile; }
    
    
    // Write a record to the file
    int WriteRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fwrite(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    // read a record from the file
    int ReadRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fread(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    
    ////////////////////////////////////////////////////////
    // this is for demonstration purposes only
    // you would not do this in a real program
    void InitFile(FILE* File)
     { int x, y;
       memset(&Record,sizeof(Record),0);
       for (x = 0; x < 1000; x++)
          { Record.randnum = rand();
            for (y = 0; y < ((Record.randnum % 15) + 1); y++)
              Record.word[y] = (rand() % 26) + 'a';
            Record.word[y] = 0;
            if (! WriteRecord(File,x))
              printf("Oh drat!");  } }
     
    
     
    //////////////////////////////////////////////////////////
    // program mains
    //
    int main (void)
      { FILE *File;
        int Quit = 0;
        int Rec = 0; // record number
    
        srand(time(NULL));
    
        File = FileOpen(FNAME); 
        if (!File)
          { printf("Curses foiled again!\n\n");
            exit(-1); }
    
        // write out 1000 test records  
        printf("Create a new file? (y/n)  ");
        if ( toupper( getchar() ) == 'Y')
          InitFile(File);
      
        // lets peek
        do
          { printf("Enter a record number (0 - 999) to load : ");
            if (! scanf("%d",&Rec) )
              Quit = 1;  // enter any letter to quit
            else 
              { // read and display the record 
               if (! ReadRecord(File,Rec) ) 
                  printf("Could not read record %d\n",Rec);
                else
                  { printf("-----\n");
                    printf("Record Number : %d\n",Rec);
                    printf("Number Value  : %d\n",Record.randnum);
                    printf("Record Name   : %s\n",Record.word);
                    printf("-----\n"); 
                    getchar();
                    printf("Do you want to rename this record (y/n)? ");
                    if ( toupper( getchar() ) == 'Y')
                      { printf("Enter a new name : ");
                        if ( scanf("%s",Record.word) )
                          WriteRecord(File,Rec);  } } }
          } while (! Quit); 
    
    
        fclose(File);
        return 0; }
    Last edited by CommonTater; 09-17-2011 at 08:58 PM. Reason: the nit pickers will have a field day with this one!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 04-14-2011, 11:15 AM
  2. Create array of pointers dynamically
    By sombrancelha in forum C Programming
    Replies: 15
    Last Post: 04-03-2011, 02:54 AM
  3. Pick data from file store in array
    By swgh in forum C Programming
    Replies: 1
    Last Post: 07-10-2009, 09:57 AM
  4. Data Structure to store unlimited dynamic vectors
    By m3rk in forum C++ Programming
    Replies: 8
    Last Post: 04-22-2009, 06:12 AM
  5. Dynamically create an array?
    By Unknowntoyou000 in forum C++ Programming
    Replies: 16
    Last Post: 04-25-2008, 03:49 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21