栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++处理文本文件

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++处理文本文件

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

#include "base.h"
#include
// 包含 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;

	}
	
	// 第三种
	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 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();
	

	

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022499.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号