0
votes

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?

3
sizeof(t) just gives you the size of a pointer, because that's what t is. If you want the size of the memory you allocated for t, why not do s.length()+1 instead? - Blaze
why all this aerobics with string to char * ? string has a data() and thats probably all you need - 463035818_is_not_a_number
sizeof operator returns the static size of the type. It gets turned into a constant number at compile time (in C++ anyway, in C there is VLA). Size of pointer is usually 4 for 32 bit binaries, 8 for 64 bit binaries. - hyde
sizeof(t) -> strlen(t). But consider the second comment. - Jabberwocky

3 Answers

3
votes

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();
2
votes

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().

2
votes

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.