writing string to binary file (c_str() not working)

Hello guys,

I am trying to write a list of strings to a binary file:
1
2
3
4
5
6
7
8
9
10
string ab, ac, ad;
ab = "fly";
ac = "above";
ad = "the_rainbow";
ofstream on;
on.open("thefile", ios::binary);
on.write(ab.c_str(), 3);
on.write(ac.c_str(), 5);
on.write(ad.c_str(), 11);
on.close();

The program compiles fine, but when I want to read it to see if it's correct:
1
2
3
4
5
6
7
8
9
10
11
12
13
char* ba, *bc, *bd;
ifstream in;
in.open("thefile", ios::binary);
ba= new char[3];
bc= new char[5];
bd= new char[11];
in.read(ba, 3);
in.read(bc, 5);
in.read(bd, 11);
cout<<ba<<endl;
cout<<bc<<endl;
cout<<bd<<endl;
in.close();


when I run it, I get the words but with strange characters at the end:
fly"*
above"*
the_rainbow"*

I am suspecting the c_str() being a const char* which creates the problem?
Any help would be welcome

Thank!
You forgot to append NULL character, so cout prints garbage and your program might crash.

If you just want to print the strings, use cout.write():
cout .write(ba,3);

But I think it's better to write NULL characters to file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
string ab, ac, ad;
ab = "fly";
ac = "above";
ad = "the_rainbow";
ofstream on;
on.open("thefile", ios::binary);
on.write(ab.c_str(), 4); // +1 for null character
on.write(ac.c_str(), 6);
on.write(ad.c_str(), 12);
on.close();

//...
char* ba, *bc, *bd;
ifstream in;
in.open("thefile", ios::binary);
ba= new char[4]; // again 3 + one null character
bc= new char[6];
bd= new char[12];
in.read(ba, 4);
in.read(bc, 6);
in.read(bd, 12);
cout<<ba<<endl;
cout<<bc<<endl;
cout<<bd<<endl;
in.close();

thanks allot for your answer,
but now, if I want to convert back my ouput to a string, does string (ba) would give me ab?
Topic archived. No new replies allowed.