文件的读写操作 fstream

文件打开方式:

模式标志描述
ios::in读方式打开文件
ios:out写方式打开文件
ios::trunc把整个文件长度截断为0
ios::app在文件的尾部添加
ios::ate定位到文件尾
ios::binary二进制方式(默认是文本方式)

以上打开方式, 可以使用位操作 | 组合起来

写入文本文件

#include <iostream>
#include <string>
#include <fstream>		//文件操作

using namespace std;

//写入方式打开文本文件
void inFile() {
	string name;		//姓名
	int age;			//年龄
	ofstream outfile;	//写文件操作

	//如果没有找到ios.txt这个文件名,那么就会自动创建这个文件
	outfile.open("ios.txt", ios::out | ios::app);		//在文件尾部写操作
	//outfile.open("ios.txt", ios::out | ios::trunc);	//把整个文件长度截断为0
	//outfile.open("ios.txt", ios::out | ios::ate);		//定位到文件尾 

	while (1) {
		cout << "请输入姓名:[Ctrl+z退出]";
		cin >> name;
		if (cin.eof()) {			//输入ctrl+z
			cout << "已结束输入!" << endl;
			break;
		}
		outfile << name << "\t";	//把name变量的数据写入文本里

		cout << "请输入年龄:";
		cin >> age;
		outfile << age << endl;		//把age变量的数据写入文本里
	}

	outfile.close();				//关闭文件
}


int main(void) {
	inFile();

	system("pause");
	return 0;
}

读取文件操作

#include <iostream>
#include <string>
#include <fstream>		//文件操作

using namespace std;

//读取方式打开文本文件
void readFile() {
	string name;
	int age;
	ifstream readfile;	//读文件操作

	readfile.open("io.txt");	//打开文件

	if (readfile.fail()) {
		cout << "打开文件出错!" << endl;
		system("pause");
		exit(1);
	}

	while (1) {
		//从文件中读取数据保存到name变量里
		//如果读到空格或制表符,会自动跳过
		readfile >> name;
		if (readfile.eof()) {	//如果读到文件结束符,就跳出循环
			break;
		}
		cout << "姓名:" << name << "\t";

		readfile >> age;
		cout << "年龄:" << age << endl;		
	}

	readfile.close();	//关闭文件
}


int main(void) {
	readFile();

	system("pause");
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值