Programming: C++ Binary IO Structure(More Like .net IO)
Posted: Tue Nov 01, 2005 8:06 pm
this code will help you to make binary file handeling in c++ easier and more like C#.net or VB.net
How to use
That code above would read an int from 0x8 in example.bin and write it to 0x8 in example2.bin
Code: Select all
#include <stdio.h>
struct BinaryRW
{
FILE *BinRW;
void Open(const char *filename)
{
BinRW=fopen(filename, "r+b");
}
void Close()
{
fclose(BinRW);
}
void Seek(int position, int fromwhere=0)
{
// 0 = From Start - 1 = From Current - 2 = From End
fseek(BinRW, position, fromwhere);
}
int GetPosition()
{
return ftell(BinRW);
}
int GetFileLength()
{
int pos=GetPosition();
Seek(0, 2);
int end=GetPosition();
Seek(pos);
return end;
}
int ReadInt32()
{
int tmp;
fread(&tmp, 4, 1, BinRW);
return tmp;
}
int ReadShort()
{
int tmp;
fread(&tmp, 2, 1, BinRW);
return tmp;
}
int ReadByte()
{
int tmp;
fread(&tmp, 1, 1, BinRW);
return tmp;
}
char *ReadChars(int size)
{
char *tmp;
fread(&tmp, size, 1, BinRW);
return tmp;
}
void WriteInt32(int theint)
{
fwrite(&theint, 4, 1, BinRW);
}
void WriteShort(int theshort)
{
fwrite(&theshort, 2, 1, BinRW);
}
void WriteByte(int thebyte)
{
fwrite(&thebyte, 1, 1, BinRW);
}
void WriteChars(const char* thechars, int thesize)
{
fwrite(&thechars, thesize, 1, BinRW);
}
};
Code: Select all
BinaryRW TheBRW;
BinaryRW TheBRW2;
TheBRW.Open("C:/example.bin");
TheBRW2.Open("C:/example2.bin");
TheBRW.Seek(8, 0);
TheBRW2.Seek(8, 0);
TheBRW2.WriteInt32(TheBRW.ReadInt32());
TheBRW.Close();
TheBRW2.Close();