• Advertisement
Sign in to follow this  

What's wrong with my code?

This topic is 3492 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have the following code that reads/writes a hole structure from/to a file. For some reason the application crashes when the program reads the data. Anyone knows why? I pasted the code on sendmecode http://sendmecode.com/?page=view&id=1215085062

Share this post


Link to post
Share on other sites
Advertisement
You're not actually writing the data stored in the string and in the vector. For example, the vector probably stores a pointer to dynamically allocated memory, but you just write the pointer (which doesn't make sense, BTW), not the actual memory. Same deal with the string.

I recommend that you use boost serialization for this, it will make your life much easier.

BTW, there's no need to call close(), the file's destructor takes care of that.

Share this post


Link to post
Share on other sites
Never ever ever just dump a non-POD variable to a file. There's so many things wrong there, I don't know where to start. The fact that you have a reinterpret_cast should already be a big hint. You should never have to use those. You're overwriting internal pointers, heap management data and God knows what.

Instead, read the data and parse it. In your case, you may use the following file format:

uint32_t block_name_length
uint32_t num_strings
char
  • block_name
    uint32_t string_length
    char
  • string
    ...
    uint32_t string_length
    char
  • string

  • And read it like:

    bool readFileData(FILE_DATA& pdata,const std::string& file_name)
    {
    std::ifstream f(file_name.c_str(), std::ios::binary);

    // Read the two counts
    uint32_t block_name_length, num_strings;
    f.read(&block_name_length, sizeof(uint32_t));
    f.read(&data_length, sizeof(uint32_t));

    // Read the block name
    char* data = new data[block_name_length];
    f.read(data, block_name_length);
    pdata.name = string(data, block_name_length);
    delete[] data;

    // Read the data strings
    pdata.resize(num_strings);
    for (size_t i = 0; i < pdata.data.size(); i++)
    {
    // Read two count
    uint32_t length;
    f.read(&length, sizeof(uint32_t));

    char* data = new data[length];
    f.read(data, length);
    pdata.data = string(data, length);
    delete[] data;
    }

    return true;
    }




    Error handling has been left out, and if you really want to be portable, use marshalling on the counts (e.g., letohl() ). Writing the data happens similarly; write the length, then the data.


    Edit: or like Gage64 said, boost, which will do this for you ;)

    Share this post


    Link to post
    Share on other sites
    Sign in to follow this  

    • Advertisement