user732274
user732274

Reputation: 1069

C++ strings to/from file

Simple question: why the following code isn't working? I would expect a string to be saved and read, but this just doesn't happen...

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

static string path = "/Users/john/Desktop/file";


main() {
string a;

a = "one\n";

fstream outStream(path.c_str(), ios::out | ios::binary);
outStream.write((char *) &a, sizeof(a));
outStream.close();

a = "two\n";

fstream inStream(path.c_str(), ios::in | ios::binary);
inStream.read((char *) &a, sizeof(a));
inStream.close();

cout << a;
return 0;}

Thanks a lot!

Upvotes: 1

Views: 195

Answers (6)

Useless
Useless

Reputation: 67723

(char *) &a

is not the character string stored inside std::string, you're just telling the compiler to treat that arbitrary address (where the std::string path object is stored) as if it were characters.

sizeof(a)

will not give the length of the string in bytes: sizeof gives the size of objects, but the std:string object is the housekeeping information for your characters, not the text itself.

Use

outStream.write(a.c_str(), a.size());

or, better,

outStream << a;

Upvotes: 2

Foggzie
Foggzie

Reputation: 9821

Change

outStream.write((char *) &a, sizeof(a));

To

outStream.write(a.c_str(), s.size());

Upvotes: 1

relaxxx
relaxxx

Reputation: 7824

use

outStream << a.c_str();

instead of

outStream.write((char *) &a, sizeof(a));

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361362

Use .c_str() and .size() in write as well:

outStream.write(a.c_str(),a.size()); 

.length() is also there, which returns same value as .size().

But why don't you simply do this:

outStream << a;

And read it as:

inStream >> a;

Upvotes: 2

antlersoft
antlersoft

Reputation: 14786

You have declare a a string, but you are trying to read and write it as if it were an array of characters. std::string is not implemented as an array of characters.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

You cant write a string as a pointer. Either use the normal stream operators (<<) or use

outStream.write(a.c_str(), a.size());

Upvotes: 6

Related Questions