suppose i have a function like this
int writetofile(wstring name, any sdata){
...
return error;
}
This function have no idea about what data would be stored but would need to know the size of the data stored in sdata
. Although it is easy to determine the type of data stored in the sdata
but i don't think there is some easy way to know about the size of data in sdata
.
i have a data structure which has members of type wstring
. Now We cant write that data structure directly to the file as it contains that wstring. As far as i have researched on internet, the best way to write wstring
or string
, is to write size first of the string and then the string. Then when i would read the string first reading the size then after this read that much of size.
for this i have made a function.
int filemanager::write(any data, fileid uid, DWORD *byteswritten) const
{
// files is a map<fileid, fileinfo> where fileinfo is a struct which has
// members including file's name and handle
// fileid is a typedef of int
if (!files.count(uid)) return -1;
if (!data.has_value()) return -2;
if (data.type() == typeid(wstring)) {
DWORD sz1, sz2;
wstring str = any_cast<wstring>(data);
size_t sz3 = str.length()*sizeof(wchar_t);
if (sz3 == 0) return -2;
if (FALSE == WriteFile(files[uid].handle, &sz3, sizeof(size_t), &sz1, NULL)){
return GetLastError();
}
if (FALSE == WriteFile(files[uid].handle, str.c_str(), sz3, &sz2, NULL) && sz2 != sz3) {
return GetLastError();
}
if (byteswritten != nullptr) *byteswritten = sz1 + sz2;
}
else {
// now if the type is not a wstring then just write it to a file
// here i would need the size of the data stored in the data
}
return 0;
}
writetofile
, your plan is to write the contents of the type contained in theany
object to a file. This will fail horribly for types that are not trivially copyable. Takestd::vector
for instance; if you copy its contents to a file, you'll likely copy 3 pointers. You need to copy the data the vector is holding in dynamically allocated memory instead. Please use a proper serialization library. Anyway, I don't see how you're going to make serialization without knowing the type work – Nealonwstring
you would have to do for any other complex type you may be passing inany
. Withany
that is an insane number of different possibilities. You could restrict the possibilities withstd::variant
, but I think you are better off heading down a different path. – Sequoia