I have a sample file which reads contents from a file. The content is in an unreadable format as shown below. When I use the read() function and cout the variable, it returns the same binary data instead of showing normal text. How to read the contents in a humanly readable format?
Here are the contents of the file (upon using the write() function) I'm reading :
LÀ ³ L¹ R
Here is the reading code :
void readBinary(){
ifstream inputFile("flights.dat", ios::in | ios::binary);
char buffer[100];
inputFile.seekg(0, ios::beg);
if(inputFile.is_open()){
inputFile.read((char *)&buffer, sizeof(buffer));
for(int i = 0; i < sizeof(buffer); i++){
cout << buffer[i];
}
}
inputFile.close();
}
Here is the code for writing the data :
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void inputData();
struct airplaneDetails {
string airplaneCode;
int totalRows, seatsInRows, firstSeats, businessSeats, economySeats;
};
int main(){
inputData();
return 0;
}
void inputData(){
ofstream outputFile("flights.dat", ios::out | ios::binary | ios::app);
if(!outputFile.is_open()){
cout << "There was an error opening the file.";
} else {
airplaneDetails airplane;
cout << "Please provide the details below :" << "\n\n";
cout << "Enter the airplane code : ";
cin >> airplane.airplaneCode;
.
.
//Assigning values to the variables
.
.
//Put the pointer at the end
outputFile.seekp(0, ios::end);
//Write the input data to the binary file
outputFile.write((char *)&airplane.airplaneCode, sizeof(airplane.airplaneCode));
outputFile.write((char *)&airplane.totalRows, sizeof(airplane.totalRows));
outputFile.write((char *)&airplane.seatsInRows, sizeof(airplane.seatsInRows));
outputFile.write((char *)&airplane.firstSeats, sizeof(airplane.firstSeats));
outputFile.write((char *)&airplane.businessSeats, sizeof(airplane.businessSeats));
outputFile.write((char *)&airplane.economySeats, sizeof(airplane.economySeats));
//Close the file handler
outputFile.close();
}
}
inputFile.gcount()to determine exactly how many bytes were read from the file.