[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();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值