C++中的文件和流

所需头文件:ios

#include<iostream>
#include<fstream>

标准库fstream中定义了三种新的数据类型:app

  • ofstream
    表示输出文件流,用于建立文件并向文件写入信息
  • ifstream
    表示输入文件流,用于从文件读取信息
  • fstream
    同时具备上面了两种数据类型的功能,能够建立文件,向文件写入信息,从文件读取信息

打开文件

从文件中读取信息或者向文件写入信息以前,必须先打开文件。函数

void open(const char *filename,ios::openmode mode);
//open()函数是fstream、ifstream、ofstream对象的一个成员

open()函数第二个参数定义文件被打开的模式,模式有一下几种:spa

  • ios::app
    追加模式,全部写入都追加到文件末尾
  • ios:ate
    文件打开后定位到文件末尾
  • ios::in
    打开文件用于读取
  • ios::out
    打开文件用于写入
  • ios::trunc
    若是该文件已经存在,其内容将在打开文件以前被截断,
    即将文件长度设为0

能够把上面的几种模式混合使用,好比,想以写入的模式打开文件,而且但愿截断文件,以防止文件已经存在,能够用下面的写法:code

ofstream afile;
afile.open("file.dat",ios::out | ios::trunc);

关闭文件

当C++程序终止时,会自动关闭刷新全部流,释放全部分配的内存,并关闭全部打开的文件。可是为了防止内存泄露,应该手动释放使用完毕的流资源。对象

void close();
//close()是fstream,ifstream,ofstream对象的一个成员

写入/读取文件

用流插入运算符<<向文件写入信息,就像使用该运算符输出信息到屏幕上同样
用流提取运算符>>从文件读取信息,就像使用该运算符从键盘输入信息同样内存

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main(int argc, char const *argv[])
{
	/* code */
	char data[100];

	ofstream  outfile;
	outfile.open("afile.txt");

	cout<<"Writing to the file"<<endl;
	cout<<"Enter your name:";
	cin.getline(data,100);

	outfile<<data<<endl;

	cout<<"Enter your age:";
	cin>>data;
	cin.ignore();//ignore()会忽略掉以前读语句留下的多余字符

	outfile<<data<<endl;

	outfile.close();

	ifstream infile;
	infile.open("afile.txt");

	cout<<"Reading from file"<<endl;
	infile>>data;
	cout<<data<<endl;

	infile>>data;
	cout<<data<<endl;

	infile>>data;
	cout<<data<<endl;

	infile.close();

	return 0;
}
//这个程序有一个问题:输入的字符串中不能包含空白字符
相关文章
相关标签/搜索