C++ Read/Write files

0.00 avg. rating (0% score) - 0 votes

Write binary data to file

using namespace std;

BYTE* buffer;

ofstream fout(“file.dat”, ios::binary);

fout.write((char *)(&buffer), sizeof(number));

fout.close();

Reference:

Simple File I/O Using C++, http://www.gamedev.net/reference/articles/article1127.asp

Write text to file

std::ofstream writer;

writer.open(L”file.txt”);

if (!writer.is_open()) //Error writing file

{

}

else //open OK, now write file

{

writer << "Hello world";

writer.close();

}

Read from text file by token

std::ifstream inp;

inp.open(L”file.txt”, std::ifstream::in);

if (!inp.fail()) //open ok, read text

{

LPCWSTR str = new wchar_t[100];

inp >> str;

inp.close();

}

Open a text file and read it contents into a string

char* readText(char* fileName)

{

std::ifstream infile;

infile.open(fileName, std::ios_base::in|std::ios_base::ate);

if (infile) //read OK

{

//prepare file for input

long file_length = infile.tellg();

infile.seekg(0, std::ios_base::beg);

infile.clear();

//read text file into string

char *str = new char[file_length];

infile.read(str, file_length);

infile.close();

return str;

}

else //read FAILED

{

return NULL;

}

}

0.00 avg. rating (0% score) - 0 votes
ToughDev

ToughDev

A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply