Tuesday, July 21, 2009

Write and Read Binary to Text File : C++

At last after a few hours did a debugging but still fail to exchange a socket buffer to another object,
Finally decided to write a socket buffer to file - then the object just read the file : abis cerita

I'am refer to this site http://www.codersource.net/cpp_file_io_binary.html
very good sample and meet my expectation
so my code be like below

// test5.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include

struct socketClass
{
unsigned char buffer[16];
int id;
};

void write_to_binary_file(socketClass p_Data);
void read_from_binary_file();

int main(int argc, char* argv[])
{
printf("Hello World!\n");

socketClass a;
a.id=50;
a.buffer[0] = 0x90;
a.buffer[1] = 0x45;
a.buffer[2] = 0xA3;
a.buffer[3] = 0xC4;

write_to_binary_file(a);
read_from_binary_file();

return 0;
}

void write_to_binary_file(socketClass p_Data)
{
fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
binary_file.write(reinterpret_cast(&p_Data),sizeof(socketClass));
binary_file.close();
}

void read_from_binary_file()
{
socketClass p_Data;
fstream binary_file("c:\\test.dat",ios::binary|ios::in);
binary_file.read(reinterpret_cast(&p_Data),sizeof(socketClass));
binary_file.close();

cout<<$p_Data$.$buffer$[0]<<$endl; // remove $
cout<<<"Rank :"<< p_Data.id<<-endl;
}

No comments: