user3007875
user3007875

Reputation: 153

C++ string to C char array for writing to binary file

I am trying to write and read string to/from binary file, but I can't understand why sizeof(t) returns 4.

//write to file
ofstream f1("example.bin", ios::binary | ios::out);
string s = "Valentin";
char* t = new char[s.length()+1];
strcpy(t, s.c_str());
cout << s.length()+1 << " " << sizeof(t) << endl; // prints 9 4
for(int i = 0; i < sizeof(t); i++)
{
    //t[i] += 100;
}
f1.write(t, sizeof(t));
f1.close();

// read from file
ifstream f2("example.bin", ios::binary | ios::in);
while(f2)
{
    int8_t x;
    f2.read((char*)&x, 1);
    //x -= 100;
    cout << x;  //print Valee
}
cout << endl;
f2.close();

It doesn't matter what size I put in char* array t, code always prints "4" as its size. What must I do to write longer than 4 bytes of data?

Upvotes: 0

Views: 1024

Answers (3)

john
john

Reputation: 87959

Here's how to do the writing code the easy way

//write to file
ofstream f1("example.bin", ios::binary | ios::out);
string s = "Valentin";
f1.write(s.c_str(), s.size() + 1);
f1.close();

EDIT the OP actually wants something like this

#include <algorithm> // for transform

string s = "Valentin";
// copy s to t and add 100 to all bytes in t
string t = s;
transform(t.begin(), t.end(), t.begin(), [](char c) { return c + 100; });
// write to file
ofstream f1("example.bin", ios::binary | ios::out);
f1.write(t.c_str(), t.size() + 1);
f1.close();

Upvotes: 3

Govind Parmar
Govind Parmar

Reputation: 21542

char *t is a pointer, not an array, so sizeof will return the size of a pointer on your machine, which is apparently 4 bytes.

The correct way to determine the length of a C-style string is to include <cstring> and use std::strlen.

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 11400

sizeof(char*) prints the size used by a pointer to (a) char(s). It's 4 on your platform.

If you need the size of the string, you should use strlen. Or, simply, s.length().

Upvotes: 2

Related Questions