// WriteBinaryFile.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <vector>
int _tmain(int argc, _TCHAR* argv[])
{
/*
* 二进制文件写数据
*
*/
std::cout << "二进制文件写数据:\n";
std::ofstream fout("a.txt", std::ios::binary);
int num = 20;
std::string str("hello, world");
fout.write((char*)&num, sizeof(int));
fout.write(str.c_str(), sizeof(char)*str.size());
for (int i = 0; i < 20;++i)
{
fout.write((char*)&i, sizeof(int));
}
fout.close();
/*
* 二进制文件读数据
*
*/
std::cout << "二进制文件读数据:\n";
std::ifstream fIn("a.txt", std::ios::binary);
int data;
char szBuf[256] = { 0 };
fIn.read((char*)&data, sizeof(int));
fIn.read(szBuf, sizeof(char)* str.size());
std::cout << data << "\n" << szBuf << std::endl;
while (!fIn.eof())
{
fIn.read((char*)&data, sizeof(int));
std::cout << data << " ";
}
fIn.close();
return 0;
}