Original Post
Is there a function or class in C++ that does exactly what C''s fread / fwrite does with structs? Thanks!
quote:
Original post by Sneftel
EDIT: whoops. Yeah.
quote:A char * is a pointer, not a string. When a buffer of memory''s initial address offset is cast to char *, sequential access is byte-wise (because the size of a char is typically a byte). So cast the address of your struct to char * and pass it to write.
Original post by Anonymous Poster
http://www.cplusplus.com/ref/iostream/ostream/write.html
This definition allows a string and a byte size.
#include <iostream>
#include <fstream>
using namespace std;
typedef struct {
int i;
char *p;
float d;
} ff;
int main() {
ofstream out("a.txt", (ios::out | ios::binary));
ifstream in("a.txt", (ios::in | ios::binary));
ff *test = new ff(); // allocate memory
test->i = 500;
test->p = "test";
test->d = 2.00432f;
char *t = (char *) test;
out.write(t, sizeof(ff));
out.close();
in.read(t, sizeof(ff));
// no need to assign back to test beacuse t == test
cout << test->i << endl;
in.close();
delete test; // delete memory
return 0;
}
struct ff{
int i;
char *p;
float d;
}; structs like a normal data type. So instead of saying
typedef struct {
int i;
char* p;
float d;
} ff;
struct ff {
int i;
char* p;
float d;
};
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more