how write a structure instance to file and then read it?

Pages: 12
> why these code is never called?

Hard to say without knowing the context.

Ideally, operator << and operator >> should be overloaded for generic output stream and generic input stream (rather than for file streams). Note: my_narrow_file_stream << my_object yields std::ostream&
almost done:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
friend std::ostream& operator << (std::ostream& lhs, const image& rhs)
    {
        DebugText("writing a image to a file");
        int stringsize=rhs.strfilename.size();
        lhs<<stringsize;
        lhs.write(reinterpret_cast< const char*>(&rhs.strfilename),rhs.strfilename.size());
        return lhs;
    }

    friend std::istream& operator >> (std::istream& lhs, image& rhs)
    {
        DebugText("reading image from a file");
        string chrfilename;
        int stringsize;
        lhs>>stringsize;
        lhs.read(reinterpret_cast<char*>(&chrfilename), stringsize);
        rhs.readimagefile(chrfilename);//FileName it's a property
        return lhs;
    }

now works fine.
i need ask: how can overloading istream\ostream for strings?
(because they are read until next space ' ' :( )
> now works fine.

Undefined behaviour does appear to work fine sometimes.

1
2
3
4
5
6
7
8
std::ostream& operator<< ( std::ostream& stm, const image& img ) { return stm << img.strfilename << '\n' ; } 

std::istream& operator>> ( std::istream& stm, image& img )
{
    // http://www.cplusplus.com/reference/string/string/getline/
    if( std::getline( stm, img.strfilename ) ) img.readimagefile( img.strfilename ) ; 
    return stm ;
}
Topic archived. No new replies allowed.
Pages: 12