xxxxxxxxxx
//writing into a binary file
//int
fstream bFile("Binary file.dat", ios::out | ios::binary);
int x = 65;
if (bFile.is_open()) {
bFile.write((char*)&x, sizeof(x));
bFile.close();
}
else cout << "Failed opening the file";
//string
fstream binaryName;
string s = "J.L";
binaryName.open("Name.dat", ios::out | ios::binary);
if (binaryName.is_open()) {
binaryName.write(s.c_str(), s.size());
binaryName.close();
}
else cout << "Unable to open the file!";
xxxxxxxxxx
#include <fstream>
int main() {
// Open the file for writing in binary mode
std::ofstream outfile("YourFilename.__", std::ios::binary);
// Write an integer to the file
int num = 42;
outfile.write((char*)(&num), sizeof(num));
// Write a floating-point number to the file
double val = 3.14159;
outfile.write((char*)(&val), sizeof(val));
// Close the file
outfile.close();
return 0;
}
xxxxxxxxxx
fstream readStringBF;
readStringBF.open("Name.dat", ios::in | ios::binary);
char n[30];
if (readStringBF.is_open()) {
readStringBF.read(n, 30);
n[readStringBF.gcount()] = NULL; //append string terminator
cout << n;
readStringBF.close();
}
else cout << "Unable to open file!";
xxxxxxxxxx
//reading from a binary file
int r;
fstream readBinaryFile;
readBinaryFile.open("Binary file.dat", ios::in | ios::binary);
if (readBinaryFile.is_open()) {
readBinaryFile.read((char*)&r, sizeof(r));
cout << r;
readBinaryFile.close();
}
else cout << "Unable to open file!";