【C++】文件操作

文件和流

文件操作需要包含头文件#include

文件类型分为两种:
文本文件:文本以文本的ASCII码形式存储在计算机中
二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能读懂

1、打开文件
ofs.open(“文件路径”,“打开方式”)

2、读或写操作
ofs<<“写入的数据”;

3、关闭文件
ofs.close();

#include<iostream>
#include<fstream>
using namespace std;
int  main()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out);

	ofs << "姓名:\t张三" << "\n";
	ofs << "性别:\t男" << "\n";
	ofs << "年龄:\t18" << "\n";

	ofs.close();
	
	
	return 0;
}

注意:路径分为绝对路径和相对路径
在这里插入图片描述
打开方式ios::out,若文件不存在则创建文件,若文件已存在,则将原先的内容清除后,写入新的内容。

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int  main()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (ifs.is_open()) {
		cout << "文件打开成功\n";
		
	}
	else {
		cout << "文件打开失败\n";
		exit(-1);
	}

	//读文件

	//第一种
	//char buf[1024] = { 0 };
	//while (ifs >> buf) {
	//	cout << buf << "\n";
	//}

	//第二种
	//char buf[1024] = { 0 };
	//while (ifs.getline(buf,sizeof(buf))) {
	//	cout << buf << "\n";
	//}

	//第三种
	//string buf;
	//while (getline(ifs, buf)) {
	//	cout << buf << "\n";
	//}

	//第四种
	char c;
	while ((c = ifs.get()) != EOF) {
		cout << c;
	}
	ifs.close();

	
	
	return 0;
}


第一种:

在这里插入图片描述

第二种:每次读取一行
在这里插入图片描述

第三种:(我喜欢用)
在这里插入图片描述

第四种:一次读取一个字符
在这里插入图片描述

读取二进制文件

#include<iostream>
using namespace std;
#include<fstream>
int main() {
	
	ifstream ifs;
	ifs.open("D:\\1.jpg",ios::binary);
	ofstream ofs;
	ofs.open("E:\\1.jpg", ios::binary);
	unsigned char buf[1024];
	int count = 0;
	while (!ifs.eof()) {
		count++;
		ifs.read((char*)&buf, 1024);
		ofs.write((char*)&buf, ifs.gcount());
	}
	cout << count;
	ifs.close();
	ofs.close();
	

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值