c++文件流操作

c++文件流操作

  • 文件流: 对文件进行读写操作

    头文件:

    类库:

    ifstream 对文件输入(读文件)

    ofstream 对文件输出(写文件)

    fstream 对文件输入或输出

文件打开方式:

模式标志描述
ios::in读方式打开文件
ios:out写方式打开文件
ios::trunc如果此文件已经存在, 就会打开文件之前把文件长度截断为0
ios::app尾部最加方式(在尾部写入)
ios::ate文件打开后, 定位到文件尾
ios::binary二进制方式(默认是文本方式)

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

写文本文件

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string name;
	int age;
	ofstream outfile;  //也可以使用fstream, 但是fstream的默认打开方式不截断文件长度

	// ofstream的默认打开方式是,  截断式写入 ios::out |  ios::trunc
	// fstream的默认打开方式是,  截断式写入   ios::out
	// 建议指定打开方式
	outfile.open("user.txt", ios::out | ios::trunc);

	while (1) {
		cout << "请输入姓名: [ctrl+z退出] ";
		cin >> name;
		if (cin.eof()) { //判断文件是否结束
			break;
		}
		outfile << name << "\t";

		cout << "请输入年龄: ";
		cin >> age;  
		outfile << age << endl;  //文本文件写入
	}

	// 关闭打开的文件
	outfile.close();

	system("pause");
	return 0;
}

读文本文件

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string name;
	int age;
	ifstream infile;
	infile.open("user.txt");

	while (1) {
		infile >> name;
		if (infile.eof()) { //判断文件是否结束
			break;
		}
		cout << name << "\t";

		infile >> age;
		cout << age << endl;  
	}

	// 关闭打开的文件
	infile.close();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值