64,637
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include "stdlib.h"
#include <fstream>
using namespace std;
int main(int argc,char** argv)
{
//文本读写
/*char s = 0x20;
ofstream outfile("data.txt",ios::_Noreplace);
if (!outfile) //!运算符重载
{
return 0;
}
//ios::app: 以追加的方式打开文件
//ios::ate: 文件打开后定位到文件尾,ios:app就包含有此属性
//ios::binary: 以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
//ios::in: 文件以输入方式打开
//ios::out: 文件以输出方式打开
//ios::nocreate: 不建立文件,所以文件不存在时打开失败
//ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
//ios::trunc: 如果文件存在,把文件长度设为0
// 可以用“或”把以上属性连接起来,如ios::out|ios::binary
// ios::beg: 文件开头
// ios::cur: 文件当前位置
// ios::end: 文件结尾
// istream &seekg(streamoff offset,seek_dir origin);
// ostream &seekp(streamoff offset,seek_dir origin);
// file1.seekg(1234,ios::cur);//把文件的读指针从当前位置向后移1234个字节
// file2.seekp(1234,ios::beg);//把文件的写指针从文件开头向后移1234个字节
for(int i=0;i<10;i++)
outfile<<i<<s; //空格是为了避免数值连接在一起加上去的,此文件大小为20字节
outfile.close();
cout<<"ok,press a key!";
//system("pause");
char data;
ifstream infile("data.txt");
if (! infile) //!运算符重载
{
return 0;
}
for(int i=0;i<10;i++)
{
infile>>data; //读数据的时候因为数据间有一个空格才能完整的读出,
infile.get(data);
char spase=0;
infile.get(spase);
cout<<data<<spase; //输出到屏幕,加上空格是为了分开数字
}
system("pause");*/
//二进制写读
ofstream outfile("data.txt",ios::trunc|ios::binary);
if (!outfile) //!运算符重载
{
return 0;
}
const char* p_str = "this is test";
int aa=1203;
outfile.write((char*)&aa,sizeof(aa));
aa=1205;
outfile.write((char*)&aa,sizeof(aa));
outfile.close();
ifstream infile("data.txt",ios::binary);
if (! infile) //!运算符重载
{
return 0;
}
memset(&aa,0,sizeof(aa));
infile.seekg(sizeof(int),ios::beg);
infile.read((char*)&aa,sizeof(aa));
cout<<aa;
infile.close();
system("pause");
return 0;
}