Archived

This topic is now archived and is closed to further replies.

Ronin Magus

New to binary files

Recommended Posts

Howdy, I''ve just started learning how to use binary files (can you believe it? In the years I''ve been programming I''ve only programmed with sequential access text files.) Anyways, I''ve hit a snag. I''ve got this little program here: writefile.cpp
  
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

struct mystruct
{
	int x, y;
	string myString;
};

int main()
{
	ofstream testfile;
	mystruct test;

	test.x = 123;
	test.y = 456;
	test.myString = "Hello!";

	testfile.open("test", ios::bin | ios::out);

		testfile.write (&test, sizeof(test));

	testfile.close();

	return 0;
}
  
and this one: readfile.cpp
  
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

struct mystruct
{
	int x, y;
	string myString;
};

int main()
{
	ifstream testfile;
	mystruct test;

	testfile.open("test", ios::bin | ios::in);

		testfile.write (&test, sizeof(test));

	testfile.close();

cout << "x: " << test.x << endl;
cout << "y: " << test.y << endl;
cout << "string: " << test.myString << endl;

	return 0;
}
  
I run writefile to create a binary file and then readfile to read it back in and cout the data. But I get these results:
  
x: 123
y: 456
string:
  
I get nothing for the string. I''m betting this has something to do with the dynamic nature of STL strings. But there has to be a workaround for storing strings in a binary file!! What''s the problem? http://roninmagus.hopto.org acronymfinder.com - Find any acronym you need!

Share this post


Link to post
Share on other sites
Are you talking about in writing to the file or writing to the screen? In writing to the file I''m not writing each member individually, but instead trying to write the entire strcture directly to the file. Is this not the way to do this? Do I have to write each member out?

As far as I know you shouldn''t have to use c_str() for cout.. at least, I haven''t to date.

http://roninmagus.hopto.org
acronymfinder.com - Find any acronym you need!

Share this post


Link to post
Share on other sites
You can only write PoD''s (Plain ol'' Datatypes) directly into a binary file. std::string is most definetly not a pod.

The reason you don''t have to use c_str for cout, is because there''s an overload operator<< that does it automatically for the basic_string template (which is what std::string is).

You can do the same thing, but you also have to provide an overloaded operator<< for any structure that has any non-PoD in it (any struct/class with virtual functions or pointers is not a PoD).

Share this post


Link to post
Share on other sites