Advertisement

Saving custom class data to file

Started by July 08, 2000 11:42 PM
1 comment, last by vbisme 24 years, 5 months ago
I''ve been trying to save custom-created to a file but kept getting a problem. I used the functions fopen(), fclose(), fwrite(), and fread() in the "stdio.h" to do the file manipulations. When I try to save the build in types such as an int or an array of int everything works well, but when I try to save custom-built classes it gave me an error. Example: #include #include class Test { public: int x; int y; }; int main() { Test test1, test2; test1.x = 5; test1.y = 10; FILE *fp; if ((fp = fopen("test.tes", "wb")) == NULL) { fprintf(stderr, "Error opening file."); exit(1); }//end if if (fwrite(test1, sizeof(Test), 1, fp) != 1) { fprintf(stderr, "Error writing to file."); exit(1); }//end if fclose(fp); if ((fp = fopen("test.tes", "rb")) == NULL) { fprintf(stderr, "Error opening file."); }//end if if (fread(test2, sizeof(Test), 1, fp) != 1) { fprintf(stderr, "Error reading file."); exit(1); }//end if fclose(fp); return(0); } When compiled the error comes in the lines: if (fwrite(test1, sizeof(Test), 1, fp) != 1) and if (fread(test2, sizeof(Test), 1, fp) != 1) saying... Compiling... app.cpp C:\app.cpp(34) : error C2664: ''fwrite'' : cannot convert parameter 1 from ''class Test'' to ''const void *'' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called C:\app.cpp(47) : error C2664: ''fread'' : cannot convert parameter 1 from ''class Test'' to ''void *'' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called Error executing cl.exe. app.exe - 2 error(s), 0 warning(s) Even if I tried: fwrite((void*)test1, sizeof(Test), 1 fp it gives me... error C2440: ''type cast'' : cannot convert from ''class Test'' to ''void *'' No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called Someone help me figure out what''s wrong with the codes or if you have a different way of saving custom-built classes to files it would be great.
Hi !
Try fopen((void*)&test1,sizeof(test),1,fp) ,
what you were doing was to try interprete the class data
as a pointer, which is not too good

PestilencE
- just to have something in here
Advertisement
Bit of a warning here, yes using fopen((void*)&test1,sizeof(test),1,fp) will correct your code. However, using classes this way is a bit dangerous. As soon as you add a ''virtual'' function to your class, the compiler will add a virtual table pointer to it. Breaking your save code

Typically, you can add a ''save'' and ''load'' function to your class, and your code can ask the class to save and load itself which can look neater.

Of course, you might never add a virtual table pointer but I just wanted to warn you

n!

This topic is closed to new replies.

Advertisement