Re: [Dev-C++] A bit stumped on binary files
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Jorge A. <jor...@ep...> - 2004-05-22 03:10:12
|
In fopen you can specify a binary stream with the b modifier in the=20 wanted open type (glibc reference). Ewald Horn escribi=F3: > Hi, > =20 > I use the attached code to output a struct to a binary file.=20 > Outputting character arrays is no problem, but how do I output an=20 > integer value in bytes and not a string value ? I will be using the=20 > Win32 platform, 32-bit integer, so portability is no issue. Is there=20 > an easy way to do it that would simply output the required 4 bytes ?=20 > My current test solution converts a number to a 10 digit string,=20 > padded with 0's like this : 10 would be 0000000010, but it is clumsy! > =20 > Regards > Ewald Horn > Proprietor/Eienaar : Horn Labs > Cell/Sel : 083 519 1615 > Website : http://www.hornlabs.co.za > Email/E-pos : in...@ho... <mailto:in...@ho...> > =20 > //[code] > =20 > #include <fstream> > #include <string.h> > =20 > using namespace std; > =20 > struct MyStruct > { > char name[40]; > char surname[40]; > int age; > };=20 > =20 > // global > ofstream myFile("tmp.out",ios::out | ios::binary); > =20 > void writeStruct(MyStruct); > int main() > { > MyStruct data[3] =3D {0}; > =20 > for (int i =3D 0; i < 3; i++) > writeStruct(data[i]); > =20 > myFile.close(); > =20 > return 0; > }=20 > =20 > void writeStruct(MyStruct strc) > { > for (int i =3D 0; i < sizeof(strc.name); i++) > myFile.put(strc.name[i]); > =20 > for (int i =3D 0; i < sizeof(strc.surname); i++) > myFile.put(strc.surname[i]); > // problem area follows =20 > myFile << strc.age; > }=20 > //[end code] |