Writing to binary files

#include <iostream> #include <fstream> using namespace std; class info { private: char name[15]; char surname[15]; int age; public: void input(){ cout<<"Your name:"<<endl; cin.getline(name,15); cout<<"Your surname:"<<endl; cin.getline(surname,15); cout<<"Your age:"<<endl; cin>>age; to_file(name,surname,age); } void to_file(char name[15], char surname[15], int age){ fstream File ("example.bin", ios::out | ios::binary | ios::app); // I doesn't know how to fill all variables(name,surname,age) in 1 variable (memblock) //example File.write ( memory_block, size ); File.close(); } }; int main(){ info ob; ob.input(); return 0; } 

I donโ€™t know how to write more than 1 variable to a file, please help, I included an example;) Maybe there are more efficient ways to write to a file, please help me with this, it's hard for me to decide.

+7
source share
2 answers

For a text file, you can easily output one variable per line using a similar << to the one you use with std::cout .

For a binary, you need to use std::ostream::write() , which writes a sequence of bytes. For your age attribute, you will need reinterpret_cast this for const char* and write as many bytes as needed to store the int for your machine architecture. Please note: if you intend to read this binary date on another machine, you will have to take the word size and endianness . I also recommend that you clear the name and surname buffers before using them, so that you don't get artifacts of uninitialized memory in your binary.

In addition, there is no need to pass class attributes to the to_file() method.

 #include <cstring> #include <fstream> #include <iostream> class info { private: char name[15]; char surname[15]; int age; public: info() :name() ,surname() ,age(0) { memset(name, 0, sizeof name); memset(surname, 0, sizeof surname); } void input() { std::cout << "Your name:" << std::endl; std::cin.getline(name, 15); std::cout << "Your surname:" << std::endl; std::cin.getline(surname, 15); std::cout << "Your age:" << std::endl; std::cin >> age; to_file(); } void to_file() { std::ofstream fs("example.bin", std::ios::out | std::ios::binary | std::ios::app); fs.write(name, sizeof name); fs.write(surname, sizeof surname); fs.write(reinterpret_cast<const char*>(&age), sizeof age); fs.close(); } }; int main() { info ob; ob.input(); } 

An example data file might look like this:

 % xxd example.bin 0000000: 7573 6572 0000 0000 0000 0000 0000 0031 user...........1 0000010: 3036 3938 3734 0000 0000 0000 0000 2f00 069874......../. 0000020: 0000 .. 
+15
source
 File.write(name, 15); File.write(surname, 15); File.write((char *) &age, sizeof(age)); 
+5
source

All Articles