Reputation: 61
I try to write a char[] to a binary file, this is my method, for an int, a float, a double, and a char*
friend ofstream& operator<<(ofstream& outB, Test& t) {
//scriem int, float si double normal
outB.write((char*)&t.i, sizeof(int));
outB.write((char*)&t.f, sizeof(float));
outB.write((char*)&t.d, sizeof(double));
//scriem stringul ca un char ( +1 pentru \0)
outB.write(t.s.c_str(), t.s.size() + 1);
//scriem charul
int nrCHAR = strlen(t.c) + 1;
outB.write((char*)&nrCHAR, sizeof(int));
outB.write(t.c, strlen(t.c) + 1);
return outB;
}
I can do it like this?
outB.write(c, strlen(c) + 1);
c being my char[]
Upvotes: 0
Views: 424
Reputation: 57678
Usually, text fields are variable length, so you will have to write the length and the text. Here's my suggestion:
const uint32_t length = strlen(c);
outB.write((char *) &length, sizeof(length));
outB.write(c, length);
When reading, you can do the reverse:
const uint32_t length = 0;
inpB.read((char *) &length, sizeof(length));
char * text = new char [length + 1];
inpB.read(&text[0], length);
text[length] = '\0';
A nice feature of writing the length first, is that you can allocate dynamic memory for the string before reading the text. Also, since the length of the text is known, a block read can be performed.
When using a sentinel character, like '\0'
, you have to read character by character until the sentinel is read. This is slow, really slow. You may also have to reallocate your array, since you don't know the size of the string.
Upvotes: 2