Results 1 to 6 of 6

Thread: write struct to file

  1. #1

    Thread Starter
    <?="Moderator"?> john tindell's Avatar
    Join Date
    Jan 2002
    Location
    Brighton, UK
    Posts
    1,099

    write struct to file

    hey im trying to store data in a file from a struct? can anyone point me to how i should go about doing this, i tried like this but it says that cant convert my struct to char *
    Code:
    struct user_data{
    	char username[25];
    	char password[25];
    };
    
    ......
    
    ofstream file(USER_DATA,ios::out|ios::binary);
    file.write(ud,sizeof(ud));
    file.close();
    can someone please point me on how i should do this thanks.

  2. #2
    Hyperactive Member sw_is_great's Avatar
    Join Date
    Nov 2003
    Posts
    330
    u can do a memcpy to a character array.
    Regards

  3. #3
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Code:
    file.write((char*)&ud, sizeof(ud));
    Need to pass the address of the struct, not the struct itself.

    Watch for structure padding when you write it (for example, it may write more than 50 bytes).
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  4. #4

    Thread Starter
    <?="Moderator"?> john tindell's Avatar
    Join Date
    Jan 2002
    Location
    Brighton, UK
    Posts
    1,099
    cheers, could i do the same if i wanted to read the file into a struct?

  5. #5
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276
    Code:
    ifstream in(USER_DATA, ios::in | ios::binary);
    in.read((char*)&ud, sizeof(ud));
    in.close();

  6. #6
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276
    FYI:
    If you look at the file with a text editor you can't read the text but
    if you open it with a binary editor you can understand it.

    You may want to look at encrypting the output if you don't want it
    to easily be read.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width