For a text file, you could easily output one variable per line using a similar <<
to the one you use with std::cout
.
For a binary file, you need to use std::ostream::write()
, which writes a sequence of bytes. For your age
attribute, you'll need to reinterpret_cast
this to const char*
and write as many bytes as is necessary to hold an int
for your machine architecture. Note that if you intend to read this binary date on a different machine, you'll have to take word size and endianness into consideration. I also recommend that you zero the name
and surname
buffers before you use them lest you end up with artefacts of uninitialised memory in your binary file.
Also, there's no need to pass attributes of the class into 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();
}
A sample data file may 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 ..
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…