What is a Binary file?
A binary file is a computer file that is different form a text file. It may contain data, like a computer program, or it may be a file that stores data for a program to use. In generally, it is a machine code, compilated by the assembly language.
how to open binary file?
There are a few different ways to open a binary file. The common way is to use the Binary Editor: C++ or Windows API function.
1.bin file Editor: C++ Programm
To open a binary file with C++, you need to use the ifstream class, which is part of the standard C++ library. To use this method, you first need to include the fstream header file. Then, you can open a binary file by using the ifstream::open() member function, passing in the name or path of the file as a parameter. For example:
1.1 Open bin file
/// C++ open bin file
void getBinSize(std::string path)
{
int size = 0;
std::ifstream infile(path, std::ifstream::binary);
infile.seekg(0, infile.end);
int size= infile.tellg();
infile.seekg(0, infile.beg);
infile.close();
printf("\npath=%s,size=%d \n", path, size);
return size;
}
void readBin(std::string path, char *buf, int size)
{
std::ifstream infile(path, std::ifstream::binary);
infile.read(static_cast<char *>(buf), size);
infile.close();
}
1.2 Saving Bin File
/// C++ save bin file
void writeBin ( std::string path , char * buf , int size )
{ std::ofstream outfile ( path , std::ifstream::binary );
outfile.write((char *)(buf), size);
outfile.close();
}
1.3 Reading Bin File
// read binFile
std::string filePath= "./demo.bin";
int size = GetBinSize(filePath);
char *buf= new char[size];
readBin(filePath, buf, size);
float *fbuf = reinterpret_cast<float *>(buf);
// write binFile
std::string saveFilePath= "./demo_saved.bin";
writeBin(saveFilePath, buf, size);
delete buf;
2. Windows API function CreateFile()
Another way to open a binary file is to use the Windows API function CreateFile(). This function is part of the Windows API, which is not part of the C++ standard library. However, you can use it in your C++ programs by including the Windows.h header file. The CreateFile() function takes a variety of parameters, but the most important ones for opening a binary file are the file name or path, the desired access (for example, GENERIC_READ for reading or GENERIC_WRITE for writing), and the share mode (for example, FILE_SHARE_READ to allow other processes to read the file while your process has it open). For example:
#include Windows.h>
int main()
{
HANDLE file = CreateFile("example.bin", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
// ...
}