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