C++ Read/Write files
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;
}
}