my output file has random data when I write something on it,I checked multiple sources of writing object on a file and this seems correct still can't enter the right data
#include<bits/stdc .h>
using namespace std;
namespace fs = std::filesystem;
class Events{
char eventName[90];
public:
void setEventName(){
cout<<"set event name ";
cin>>eventName;
}
};
class EventFunctions:public Events{
public:
void WriteEvent(){
Events obj;
obj.setEventName();
ofstream outf;
outf.open("hello.txt");
outf.write((char *)&obj,sizeof(obj));
outf.close();
}
};
int main(){
EventFunctions ee;
ee.WriteEvent();
}
using devc
MinGW GCC 11.2.0
CodePudding user response:
There are a couple of issues here. First, write
does not stop at a null pointer. It prints exactly as many characters as you ask it to, and that can include the 86 characters of garbage after the \0
terminating your string. You want
outf.write(my_string, strlen(my_string));
But there's more going on here. When you write (char *)&obj
, I'm guessing that you're trying to write obj.eventName
in a clever way. But you can't do that in this case. From the C standard §11.4.1
If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member if that member is not a bit-field. Its address is also the same as the address of each of its base class subobjects.
Now, your class satisfies standard layout, so the address of obj
is guaranteed to be the address of obj.eventName
. But this is a very arcane and confusing way to write this. And if you're expecting this to somehow automatically serialize the whole class, then that won't work. C is free to add or subtract padding in classes, so your class may be slightly more than 90 bytes. And it's not guaranteed to have the same representation across machines or compiler versions, so writing the bytes of a C object to disk and then reading them back later is a very bad idea. If your goal is serialization, write a real serializer, rather than hacking together char*
casts.
CodePudding user response:
You're writing out the wrong thing. Instead of writing out an object, write out the string that the object contains. And limit the length to the actual length of the string, not the whole buffer with all its uninitialized garbage.
outf.write(&obj.eventName, strlen(obj.eventName));