文件读写详解

1. C++文件读写详解

1.1. 文件读写操作

使用方式

#include "fstream"
ofstream ofile    //文件写操作,内存写入存储设备
ifstream ifile    //文件读操作,存储设备读入内存
fstream  file    //文件读写操作
ofile.open("filename",mode)        //打开文件以及打开模式
if(!ofile){    //判断文件是否打开成功
  cout << "file open error!" << endl;
}

1.1.1. 打开文件

文件操作通过成员函数open()实现打开文件

//open
public member function  
void open ( const char * filename,  
            ios_base::openmode mode = ios_base::in | ios_base::out );  
void open(const wchar_t *_Filename,  
        ios_base::openmode mode= ios_base::in | ios_base::out,  
        int prot = ios_base::_Openprot);
  • 参数:
    filename:操作文件名
    mode:打开文件的方式
    prot:打开文件的属性 //基本很少用到,在查看资料时,发现有两种方式
    打开文件的方式在ios类(所以流式I/O的基类)中定义,有如下几种方式:
ios::in	    为输入(读)而打开文件
ios::out	为输出(写)而打开文件
ios::ate	初始位置:文件尾
ios::app	所有输出附加在文件末尾
ios::trunc	如果文件已存在则先删除该文件
ios::binary	二进制方式

这些方式是能够进行组合使用的,以“或”运算(“|”)的方式:例如

ofstream out;  
out.open("Hello.txt", ios::in|ios::out|ios::binary)                 //根据自己需要进行适当的选取  

打开文件的属性同样在ios类中也有定义:
0 普通文件,打开操作
1 只读文件
2 隐含文件
4 系统文件
对于文件的属性也可以使用“或”运算和“+”进行组合使用,这里就不做说明了。
很多程序中,可能会碰到ofstream out(“Hello.txt”), ifstream in("…"),fstream foi("…")这样的的使用,并没有显式的去调用open()函数就进行文件的操作,直接调用了其默认的打开方式,因为在stream类的构造函数中调用了open()函数,并拥有同样的构造函数,所以在这里可以直接使用流对象进行文件的操作,默认方式如下:

ofstream out("...", ios::out);  
ifstream in("...", ios::in);  
fstream foi("...", ios::in|ios::out);  

当使用默认方式进行对文件的操作时,你可以使用成员函数is_open()对文件是否打开进行验证

1.1.2. 关闭文件

当文件读写操作完成之后,我们必须将文件关闭以使文件重新变为可访问的。成员函数close(),它负责将缓存中的数据排放出来并关闭文件。这个函数一旦被调用,原先的流对象就可以被用来打开其它的文件了,这个文件也就可以重新被其它的进程所访问了。为防止流对象被销毁时还联系着打开的文件,析构函数将会自动调用关闭函数close。

1.1.3. 文本文件的读写

类ofstream, ifstream 和fstream 是分别从ostream, istream 和iostream 中引申而来的。这就是为什么 fstream 的对象可以使用其父类的成员来访问数据。
一般来说,我们将使用这些类与同控制台(console)交互同样的成员函数(cin 和 cout)来进行输入输出。如下面的例题所示,我们使用重载的插入操作符<<:

// writing on a text file
#include <fiostream.h>
int main () {
    ofstream out("out.txt");
    if (out.is_open())
    {
         out << "This is a line.\n";
         out << "This is another line.\n";
         out.close();
    }
    return 0;
}
//结果: 在out.txt中写入:
This is a line.
This is another line
// reading binary file
#include <iostream>
#include <fstream.h>
const char * filename = "test.txt";
int main () {
    char * buffer;
    long size;
    ifstream in (filename, ios::in|ios::binary|ios::ate);
    size = in.tellg();
    in.seekg (0, ios::beg);
    buffer = new char [size];
    in.read (buffer, size);
    in.close();
    cout << "the complete file is in a buffer";
    delete[] buffer;
    return 0;
}
//运行结果:
The complete file is in a buffer

1.1.4. 文件的读写指针

ofstream fout("a1.out",ios::app);  //以添加方式打开
long location = fout.tellp();    //取得写指针位置
location = 10L;
fout.seekp(location);          //将写指针移动到第十个字节处
fout.seekp(location,ios:beg);  //从头数location
fout.seekp(location,ios::cur); //从当前位置数location
fout.seekp(location,ios::end); //从尾部数location

1.1.5. 用流迭代器读取写入文件

#include "vector"
#include "string"
#include "fstream"
#include "iterator"
void practice10_29() {
	ifstream files;
	vector<string> Str;
	files.open("./hello.txt");			//打开文件
	istream_iterator<string> in_iter(files);		//定义文件输出流
	if (files.is_open())				//如果文件打开成功
		while (!files.eof()) {			//如果输入流没有到末尾
			Str.push_back(*in_iter++);	//读取输入流存储到内存中
		}
	else {
		cout << "open file failed" << endl;
	}
	files.close();
	print(Str);
}

void test10_28() {
	vector<string> Str = { "fox","red","banoria" ,"over","begin","man","hello","promise" };
	ofstream ofile;
	ofile.open("./hello.txt",ios::app);
	auto sp = Str.begin();
	ostream_iterator<string> out_iter(ofile," ");
	if(ofile.is_open())
		copy(Str.begin(), Str.end(), out_iter);
	ofile.close();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值