File I/O newbie question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • brixton
    New Member
    • Nov 2006
    • 35

    #1

    File I/O newbie question

    Hello there,

    I'm learning file I/O in c++ ATM and I'm getting a strange problem when I'm (at least I think so) following a tutorial.

    What I'm doing is simply writing a User object to a file
    and then read that same object from the file. I'm doing this just to see that the file operations work.

    Code below (place inside a member function of the User class):

    Code:
    #include <fstream>
    
    fstream f("D:/users.bin", ios::in | ios::out | ios::binary);
    
    User userpost = *this;
    User readuserpost;
    
    f.write(reinterpret_cast<char *>(&userpost), sizeof(userpost));
    
    f.seekg(0, ios::beg);
    
    f.read(reinterpret_cast<char *>(&readuserpost), sizeof(readuserpost));
    
    f.close();
    Now, the above works fine. But if I comment out the f.write() command, I get an access violation / segmentation error.
    So, I try to comment out the f.seekg() command, and now it works fine again. But I want to be able to move through the file so I really need it :) What am I doing wrong?

    Thanks!
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    From

    User userpost = *this;

    I assume this is inside a class member. I do not think this is a good way to write the data from a class to a file. At the very least it is non-portable. If the class happens to have virtual functions then it is a disaster as you will be reading an writing the vtable pointer to the file which could easily lead to undefined behaviour since there is no guarantee that the virtual function will exist in the same place from one instance to another and certainly not if you share files between computers.

    Limit yourself to writing basic types to a file and best practice is to decided if the file will be big or little endian separately to the current platform and write the data specifically in that format.

    Comment

    Working...