也可以先创建 ofstream对象, 再用 open函数 打开
ofstream fout;
fout.open( “test.out”, ios::out|ios::binary );
判断打开是否成功:
if(!fout) { cerr << “File open error!”<<endl; }
文件名可以给出绝对路径, 也可以给相对路径
没有交代路径信息, 就是在当前文件夹下找文件
文件的读写指针
对于输入文件,有一个读指针
对于输出文件, 有一个写指针
对于输入输出文件, 有一个读写指针
标识文件操作的当前位置,
该指针在哪里 读写操作就在哪里进行
文件的读写指针
ofstream fout(“a1.out”, ios::app);
long location = fout.tellp(); //取得写指针的位置
location = 10L;
fout.seekp(location); // 将写指针移动到第10个字节处
fout.seekp(location, ios::beg); //从头数location
fout.seekp(location, ios::cur); //从当前位置数location
fout.seekp(location, ios::end); //从尾部数location
location 可以为负值
文件的读写指针
ifstream fin(“a1.in”,ios::in);
long location = fin.tellg(); //取得读指针的位置
location = 10L;
fin.seekg(location); //将读指针移动到第10个字节处
fin.seekg(location, ios::beg); //从头数location
fin.seekg(location, ios::cur); //从当前位置数location
fin.seekg(location, ios::end); //从尾部数location
location 可以为负值
二进制文件读写
int x=10;
fout.seekp(20, ios::beg);
fout.write( (const char *)(&x), sizeof(int) );
fin.seekg(0, ios::beg);
fin.read( (char *)(&x), sizeof(int) );
二进制文件读写, 直接写二进制数据, 记事本看未必正确
10
// File_Read_Write.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include<cstring>
using namespace std;
class student
{
public:
char str[20];
int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
student student_buffer;
/*二进制文件的写*/
ofstream outfile;
outfile.open("test.dat",ios::out|ios::binary);//打开文件二进制方式
while(cin>>student_buffer.str>>student_buffer.a)
{
if(!strcmp(student_buffer.str,"exit"))
break;
outfile.write((const char*)(&student_buffer),sizeof(student_buffer));
}
outfile.close();
/*二进制文件的读*/
ifstream infile;
infile.open("test.dat",ios::in|ios::binary);
if(!infile)
{
cout<<"open the test.dat file eror!!!"<<endl;
return 0;
}
while(infile.read((char*)(&student_buffer),sizeof(student_buffer)))
{
int bits=infile.gcount();//查看读入了多少字节
cout<<bits<<endl;
cout<<student_buffer.str<<student_buffer.a<<endl;
}
infile.close();
/*二进制文件的读写*/
fstream iofile;
iofile.open("test.dat",ios::in|ios::out|ios::binary);
if(!iofile)
{
cout<<"open the test.dat file eror!!!"<<endl;
return 0;
}
iofile.seekp(2*sizeof(student_buffer),ios::beg);//将写指针移动到将要改写的地方
iofile.write("Mike",strlen("Mike")+1);
iofile.seekg(0,ios::beg);//将读指针移动到开始
while(iofile.read((char*)&student_buffer,sizeof(student_buffer)))
{
cout<<student_buffer.str<<student_buffer.a<<endl;
}
iofile.close();
return 0;
}