c++处理文本文件

c++处理文本文件时,需引用头文件
文件类型分为两种,一种是文本文件,一种是二进制文件
文本文件:文件以文本的ascii码形式存储在计算机中
二进制文件:文件以文本的二进制存储在计算机中
ofstream :写操作
ifstream: 读操作
fstream: 读写操作
在这里插入图片描述
在这里插入图片描述在这里插入图片描述

#include "base.h"
#include<string>
// 包含 fstream 头文件
int main() {
	ofstream ofs;
	// 写文件
	//ofs.open("toto.txt", ios::in);
	//ofs << "hello worldhello";
	//ofs.close();

	//读文件
	ifstream ifs;
	ifs.open("toto.txt", ios::in);
	if (!ifs.is_open()) {
		cout << "open fail" << endl;

	}
	/*
	// 第一种
	char buf[1024];
	while (ifs >> buf) {  //一行一行读 读到头了返回false
		cout << buf << endl;
	}


	// 第二种
	char buf2[1024];
	while (ifs.getline(buf2, sizeof(buf2))) {
		cout << buf2 << endl;
	}*/
	// 第三种
	string buf3;
	while (getline(ifs, buf3)) {
		cout << buf3 << endl;
	}


	ifs.close();
}

二进制文件操作
以二进制的方式对文件进行操作时,打开方式要指定为ios::binary
写文件:
二进制方式写文件主要利用流对象调用成员函数write
函数原型: ostream & write(const char * buf, int len);
字符指针buf指向内存中的一段存储空间,len是读写的字节数

读同理 ostream & read(char * buf,int len);
buf指向内存中一段存储空间,len是读写的字节数
在这里插入图片描述

在这里插入图片描述

int main() {
	Pokemon p1[2];
	p1[0].type = "水";
	p1[0].level = 50;
	p1[0].name = "水箭龟";
	p1[1].type = "火";	
	p1[1].level = 60;
	p1[1].name = "喷火龙";

	ofstream ofs;
	ofs.open("pokemon.txt", ios::out);
	for (int i = 0; i < 2; i++) {
		ofs << p1[i].name << " " << p1[i].type << " " << p1[i].level << endl;
	}
	ofs.close();

	ifstream ifs;
	ifs.open("pokemon.txt", ios::in);
	if (!ifs.is_open()) {
		cout << "open file" << endl;
	}
	/*
	string buf;
	while (getline(ifs, buf)) {
		cout << buf << endl;
	} */
	
	string name;
	string type;
	int level;
	while (ifs >> name && ifs >> type && ifs >> level) {
		Pokemon* poke = NULL;
		poke = new Pokemon(name, type, level);
		cout << poke->name << poke->type << poke->level << endl;
	}
	ifs.close();
	/*
	// binary 写
	ofs.open("pokemon2.txt", ios::out | ios::binary);
	ofs.write((const char*)&p1[1], sizeof(p1[1]));
	ofs.write((const char*)&p1[0], sizeof(p1[0]));
	ofs.close();

	// binary 读
	ifs.open("pokemon2.txt", ios::in | ios::binary);
	if (!ifs.is_open()) {
		cout << "dont get it" << endl;
	}
	Pokemon p3;
//	Pokemon p4;
	ifs.read((char*)&p3, sizeof(p3));
//	ifs.read((char*)&p4, sizeof(p4));
	cout << p3.name << p3.level << p3.type << endl;
//	cout << p4.name << p4.level << p4.type << endl;
	ifs.close();
	*/

	

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值