Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Writing Objects into files in binary mode

Writing Objects into files in binary mode

Scheduled Pinned Locked Moved C / C++ / MFC
helpios
5 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Sujan Dhakal
    wrote on last edited by
    #1

    Writing Object Succeeds with the following code

    #include <iostream>
    #include <fstream>
    using namespace std;

    class Data
    {
    public:
    string name;
    int id;
    public:
    Data(){}
    Data(string n,int id){name=n;this->id=id;}
    };

    int main() {

    Data objdata("sujan dhakal",1);
    fstream file("c:\\\\test.txt",ios::out | ios::binary);
    if(file.is\_open())
    {
    	file.write((char\*)&objdata,sizeof(Data));
    	cout<<"Success";
    	file.close();
    }
    else
    {
    	cout<<"Error";
    }
    
    return 0;
    

    }

    but why reading not working #include <iostream> #include <fstream> using namespace std; class Data { public: string name; int id; public: Data(){} Data(string n,int id){name=n;this->id=id;} }; int main() { Data objdata; fstream file("c:\\test.txt",ios::in | ios::binary); if(file.is_open()) { file.read((char*)&objdata,sizeof(Data)); cout<<objdata.name<<objdata.id<<endl; cout<<"Success"; file.close(); } else { cout<<"Error"; } return 0; } help me

    C CPalliniC 2 Replies Last reply
    0
    • S Sujan Dhakal

      Writing Object Succeeds with the following code

      #include <iostream>
      #include <fstream>
      using namespace std;

      class Data
      {
      public:
      string name;
      int id;
      public:
      Data(){}
      Data(string n,int id){name=n;this->id=id;}
      };

      int main() {

      Data objdata("sujan dhakal",1);
      fstream file("c:\\\\test.txt",ios::out | ios::binary);
      if(file.is\_open())
      {
      	file.write((char\*)&objdata,sizeof(Data));
      	cout<<"Success";
      	file.close();
      }
      else
      {
      	cout<<"Error";
      }
      
      return 0;
      

      }

      but why reading not working #include <iostream> #include <fstream> using namespace std; class Data { public: string name; int id; public: Data(){} Data(string n,int id){name=n;this->id=id;} }; int main() { Data objdata; fstream file("c:\\test.txt",ios::in | ios::binary); if(file.is_open()) { file.read((char*)&objdata,sizeof(Data)); cout<<objdata.name<<objdata.id<<endl; cout<<"Success"; file.close(); } else { cout<<"Error"; } return 0; } help me

      C Offline
      C Offline
      Cedric Moonen
      wrote on last edited by
      #2

      I suggest you read this series of articles[^]. They are about serrialization, this is what you need to do in order to save/load objects.

      Cédric Moonen Software developer
      Charting control [v3.0] OpenGL game tutorial in C++

      S 1 Reply Last reply
      0
      • C Cedric Moonen

        I suggest you read this series of articles[^]. They are about serrialization, this is what you need to do in order to save/load objects.

        Cédric Moonen Software developer
        Charting control [v3.0] OpenGL game tutorial in C++

        S Offline
        S Offline
        Sujan Dhakal
        wrote on last edited by
        #3

        i'm writing a simple program using Ansi C++. I'm not using Microsoft C++. that doesnot applies to me. what's your suggestion?

        1 Reply Last reply
        0
        • S Sujan Dhakal

          Writing Object Succeeds with the following code

          #include <iostream>
          #include <fstream>
          using namespace std;

          class Data
          {
          public:
          string name;
          int id;
          public:
          Data(){}
          Data(string n,int id){name=n;this->id=id;}
          };

          int main() {

          Data objdata("sujan dhakal",1);
          fstream file("c:\\\\test.txt",ios::out | ios::binary);
          if(file.is\_open())
          {
          	file.write((char\*)&objdata,sizeof(Data));
          	cout<<"Success";
          	file.close();
          }
          else
          {
          	cout<<"Error";
          }
          
          return 0;
          

          }

          but why reading not working #include <iostream> #include <fstream> using namespace std; class Data { public: string name; int id; public: Data(){} Data(string n,int id){name=n;this->id=id;} }; int main() { Data objdata; fstream file("c:\\test.txt",ios::in | ios::binary); if(file.is_open()) { file.read((char*)&objdata,sizeof(Data)); cout<<objdata.name<<objdata.id<<endl; cout<<"Success"; file.close(); } else { cout<<"Error"; } return 0; } help me

          CPalliniC Offline
          CPalliniC Offline
          CPallini
          wrote on last edited by
          #4

          You cannot do that. You're trying to serialize an object (see "Serialization" topic at Wikipedia [^]) in a wrong way. Since std::string is not a scalar type, the object instance (objdata) holds just a reference to it (and you're saving just such a reference, i.e. storing an address to disk, clearly it makes no sense). So you cannot save the class as a whole using

          file.write((char*)&objdata,sizeof(Data));

          instead you have to store each of its members in order to restore appropriately them, for instance:

          file.write((char*)&(objdata.id),sizeof(objdata.id));
          string::size_type len = objdata.name.length();
          file.write((char*) &len, sizeof(len)); // this is useful for reading back the string
          file.write((char*)(objdata.name.c_str(), len); //note: not storing null terminator

          Can you spot the code for reading back the class? :)

          If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
          This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
          [My articles]

          In testa che avete, signor di Ceprano?

          S 1 Reply Last reply
          0
          • CPalliniC CPallini

            You cannot do that. You're trying to serialize an object (see "Serialization" topic at Wikipedia [^]) in a wrong way. Since std::string is not a scalar type, the object instance (objdata) holds just a reference to it (and you're saving just such a reference, i.e. storing an address to disk, clearly it makes no sense). So you cannot save the class as a whole using

            file.write((char*)&objdata,sizeof(Data));

            instead you have to store each of its members in order to restore appropriately them, for instance:

            file.write((char*)&(objdata.id),sizeof(objdata.id));
            string::size_type len = objdata.name.length();
            file.write((char*) &len, sizeof(len)); // this is useful for reading back the string
            file.write((char*)(objdata.name.c_str(), len); //note: not storing null terminator

            Can you spot the code for reading back the class? :)

            If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
            This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
            [My articles]

            S Offline
            S Offline
            Sujan Dhakal
            wrote on last edited by
            #5

            so it was only the issue of std::string class, thanks i succeed with the following code.

            #include <iostream>
            #include <fstream>
            #include <cstring>
            using namespace std;

            class Data
            {
            public:
            char name[20];
            int id;
            public:
            Data(){}
            Data(char *n,int id){strcpy(name,n);this->id=id;}
            };

            int main() {

            Data objdata;
            //fstream file("c:\\\\test.txt",ios::out | ios::binary);
            fstream file("c:\\\\test.txt",ios::in | ios::binary);
            if(file.is\_open())
            {
            	//file.write((char\*)&objdata,sizeof(Data));
            
            	file.read((char\*)&objdata,sizeof(Data));
            	cout<<objdata.name<<objdata.id;
            	cout<<"Success";
            	file.close();
            }
            else
            {
            	cout<<"Error";
            }
            
            return 0;
            

            }

            1 Reply Last reply
            0
            Reply
            • Reply as topic
            Log in to reply
            • Oldest to Newest
            • Newest to Oldest
            • Most Votes


            • Login

            • Don't have an account? Register

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • World
            • Users
            • Groups