I have a homework and I have to write an object into a binary file. Then I have to read that object from the binary file. Everything works fine,except a variable of type char*. I read it, but at the end of the text i got some random characters. I think the problem is the string terminator /0 ,but i don't know how to handle it. Can someone help me?
This is the code I used to write in the file:
size_t n = strlen(input);// input is declared as char* input
f.write((char*)&n, sizeof(n+1));
f.write(input, n);
And this is how I tried to read this variable from the binary file:
size_t n;
f.read((char*)&n, sizeof(n));
delete[] buffer;// buffer is also a char*
buffer = new char[n];
f.read(buffer, n);
I got the text from variable input, but at the end i got some random characters
sizeof(n+1)doesn't do what you think it does, but I dont think that relates to your problemsizeof(n+1)-- No need to read any further. This is totally wrong.f.write((char*)&n, sizeof(n+1));you broke file by writing extra byte with unknown content