[C++之文件操作] ifstream,ofstream,fstream

文件操作总是包含三个基本步骤:

  • 打开文件
  • 读\写文件
  • 关闭文件

打开文件

打开文件操作包括:建立文件流对象,与外部文件关联,指定文件打开方式。
方法一:先建立流对象,然后调用open函数连接外部文件

流类对象名
对象名.open( 文件名,方式);

方法二:调用流类带参数的构造函数,建立时就连接外部文件

流类对象名( 文件名,方式);

其中文件打开方式表:

标识常量 含义
ios::in 读方式
ios::out 写方式
ios::ate 打开文件时,文件指针指向文件末尾
ios::app 追加方式,将向文件中的输出内容追加到文件尾部
ios::trunc 删除文件现有的内容
ios::nocreate 如果文件不存在,则打开操作失败
ios::noreplace 如果文件存在,则打开操作失败
ios::binary 以二进制代码方式打开,默认为文本方式

举例:打开一个已有文件datafile.txt,准备读:

ifstream infile;
infile.open("datafile.txt", ios::in);

打开(创建)一个文件datafile.txt,准备写:

ofstream outfile;
outfile.open("datafile.txt", ios::out);

文本文件处理

在文本文件中通常将一个记录放在一行(用换行符分割的逻辑行)。记录的每个数据项之间可以用空白符,换行符,制表符等作为分隔符。
【举例1】建立一个包含学生学号、姓名、成绩的文本文件,本例程一行放一个学生记录。

int main() {
	string fileName = ".\\temp\\students.txt";
	
	ofstream outfile;
	outfile.open(fileName, ios::out);

	//调用重载算符函数测试流
	if (!outfile) {
		cerr << "File could not be open." << endl;
		abort();
	}
	outfile << "This is a file of students\n";
	cout << "Input the number, name, and score:"
		<< "(Enter Ctrl+Z to end input)\n";

	int number, score;
	string name;
	while (cin >> number >> name >> score) {
		outfile << number << ' ' << name << ' ' << score << endl;
	}

	outfile.close();
}

【举例2】将上述创建的文件内容打印出来

int main() {
	string fileName = ".\\temp\\students.txt";
	
	ifstream infile;
	infile.open(fileName, ios::in);

	//调用重载算符函数测试流
	if (!infile) {
		cerr << "File could not be open." << endl;
		abort();
	}

	int number, score;
	string name;
	char title[80];
	infile.getline(title, 80); //略去标题
	while (infile >> number >> name >> score) {
		cout << number << ' ' << name << ' ' << score << endl;
	}

	infile.close();
}

你可能感兴趣的:(C++)