Reading/writing files to/from a struct/class

前端 未结 2 1638
死守一世寂寞
死守一世寂寞 2021-01-16 05:52

I\'d like to read a file into a struct or class, but after some reading i\'ve gathered that its not a good idea to do something like:

int MyClass::loadFile(          


        
2条回答
  •  日久生厌
    2021-01-16 06:03

    The preferred general technique is called serialization.

    It is less brittle than a binary representation. But it has the overhead of needing to be interpreted. The standard types work well with serialization and you are encouraged to make your class serialize so that a class containing your class can easily be serialized.

    class MyClass {
         int x;
         float y;
         double z;
         friend std::ostream& operator<<(std::ostream& s, MyClass const& data);
         friend std::istream& operator>>(std::istream& s, MyClass& data);
    };
    
    std::ostream& operator<<(std::ostream& s, MyClass const& data)
    {
        // Something like this
        // Be careful with strings (the input>> and output << are not symmetric unlike other types)
        return str << data.x << " " << data.y << " " << data.z << " ";
    }
    
    // The read should be able to read the version printed using <<
    std::istream& operator>>(std::istream& s, MyClass& data)
    {
        // Something like this
        // Be careful with strings.
        return str >> data.x >> data.y >> data.z;
    }
    

    Usage:

    int main()
    {
        MyClass   plop;
        std::cout << plop;  // write to a file
        std::cin  >> plop;  // read from a file.
    
    
        std::vector  data;
    
        // Read a file with multiple objects into a vector.
        std::ifstream  loadFrom("plop");
        std::copy(std::istream_iterator(loadFrom), std::istream_iterator(),
                  std::back_inserter(data)
                 );
    
    
        // Write a vector of objects to a file.
        std::ofstream   saveTo("Plip");
        std::copy(data.begin(), data.end(), std::ostream_iterator(saveTo));
    
        // Note: The stream iterators (std::istream_iterator) and (std::ostream_iterator)
        //       are templatized on your type. They use the stream operators (operator>>)
        //       and (operator<<) to read from the stream.
    }
    

提交回复
热议问题