Simple Binary File I/O Read and Write
So.... I haven't programmed in C++ for
over a year (focused on other things) so to get back into the hang of things I just decided to make some real simple binary file i/o stuff.
It writes bytes, words and dwords to a specified offset in a file and will read whatever you want. Not idiot-proof, as in it will probably crash if you do something stupid.
main.cpp
#include "fileIO.h"
//just a test program
int main()
{
cout << "WritesBytes version 1.0\nEnter file name:";
fstream FILE;
string filename;
cin >> filename;
FILE.open(filename.c_str(), ios::in | ios::out | ios::binary);
writeData16(FILE,0x2A,50000);
cout << "Wrote:" << readData(FILE,0x2A,word) << '\n';
cin>> filename;
FILE.close();
return 0;
}
fileIO.h
#ifndef FILEIO_H
#define FILEIO_H
#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
//codes
#define byte 0
#define word 1
#define dword 2
using namespace std;
typedef DWORD int32;
typedef WORD int16;
typedef BYTE int8;
void writeData32(fstream&, int, int32);
void writeData16(fstream&, int, int16);
void writeData8(fstream&, int, int8);
int readData(fstream&, int, int);
#endif
fileIO.cpp
#include "fileIO.h"
void writeData32(fstream& File, int location, int32 data)
{
if(File.is_open() == false)
{
cout << "Enter file:";
string temp; cin >> temp;
File.open(temp.c_str(), ios::in | ios::out | ios::binary);
if(!File) { cout << "File Error. Exiting.\n"; exit(1); } //won't bother troubleshooting
}
File.seekp(location); //point to the location to write
File.write((char*)&data,sizeof(int32)); //writes data, specifies 4 bytes to be written
}
void writeData16(fstream& File, int location, int16 data)
{
if(File.is_open() == false)
{
string temp; cin >> temp;
File.open(temp.c_str(), ios::in | ios::out | ios::binary);
if(!File) { cout << "File Error. Exiting.\n"; exit(1); } //won't bother troubleshooting
}
File.seekp(location); //point to the location to write
File.write((char*)&data,sizeof(int16)); //writes data, specifies 2 bytes to be written
}
void writeData8(fstream& File, int location, int8 data)
{
if(File.is_open() == false)
{
string temp; cin >> temp;
File.open(temp.c_str(), ios::in | ios::out | ios::binary);
if(!File) { cout << "File Error. Exiting.\n"; exit(1); } //won't bother troubleshooting
}
File.seekp(location); //point to the location to write
File.write((char*)&data,sizeof(int8)); //writes data, specifies 1 byte to be written
}
int readData(fstream& File, int location, int size)
{
int value;
if(File.is_open() == false)
{
string temp; cin >> temp;
File.open(temp.c_str(), ios::in | ios::out | ios::binary);
if(!File) { cout << "File Error. Exiting.\n"; exit(1); } //won't bother troubleshooting
}
File.seekp(location); //point to location to read from
if(size == byte)
File.read((char*)&value,sizeof(int8));
else if(size == word)
File.read((char*)&value,sizeof(int16));
else
File.read((char*)&value,sizeof(int32));
return value;
}