C++文件操作_字符文件 及 控制符

操作文件的三大类

  • ifstream 读操作
  • ofstream 写操作
  • fstream 读写操作

基本步骤
与我在JAVA中讲的步骤基本一致
包含头文件

#include<fstream>

选择流

ofsteam ofs;

打开文件

ofs.opean("文件路径"""打开方式)

操作

ofs<<"写入数据"

关闭流

ofs.close()

在这里插入图片描述

写入

#include<iostream>
#include<fstream>
using namespace std;
int main() {
	//选择流
	ofstream ofs;
	//打开文件
	ofs.open("test.txt", ios::out);
	//操作
	ofs << "你好,C++"            << endl;
	ofs << "这是我认识你的第18天" << endl;
	ofs << "一起努力吧!"         << endl;
	//关闭流
	ofs.close();
}

在这里插入图片描述

读取

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
	//选择流
	ifstream ifs;
	//选择源
	ifs.open("C:/unintall.log", ios::in);
	//操作
	if (!ifs.is_open()) {

		cout << "文件打开失败" << endl;
		return 0;
	}
	//按行读取
	/*char buffer[1024] = { NULL };
	while (ifs.getline(buffer, sizeof(buffer))) {
		cout << buffer << endl;
	}*/

	//以字符串读取
	string buf = { NULL };
	while ( getline(ifs,buf)) {
		cout << buf << endl;
	}

	//关闭流
	ifs.close();
}

在这里插入图片描述


操作符
在这里插入图片描述
流成员函数
在这里插入图片描述

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


int main() {
	int num = 18;
	double test = 1556216.31616;

	cout << "流成员函数" << endl;
	cout.width(15);
	cout.fill('*');
	cout.setf(ios::left);
	//1.宽15 空白‘*’
	cout << num << endl;
	cout.fill();
	//2.10 8 16 进制
	cout.setf(ios::dec);
	cout << num << endl;
	cout.unsetf(ios::dec);
	cout.setf(ios::oct);
	cout << num << endl;
	cout.unsetf(ios::oct);
	cout.setf(ios::hex);
	cout << num << endl;
	cout.unsetf(ios::hex);
	//3.精度
	cout.precision(4);
	cout.setf(ios::scientific);
	cout << test << endl;
	cout.unsetf(ios::scientific);
	cout.setf(ios::fixed);
	cout << test << endl;
	cout.unsetf(ios::fixed);
	cout << "控制符" << endl;
	//1.
	cout <<setiosflags(ios::left) << setw(15) << setfill('*') << num << endl;//1
	//2
	cout << dec << num << endl;
	cout << oct << num << endl;
	cout << hex << num << endl;
	//3

	cout << setprecision(4) << setiosflags(ios::scientific) << test << endl;
	cout << test <<endl;
	cout << setprecision(4) << setiosflags(ios::fixed) << test << endl;
	
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值