首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >C++读写文件操作(fstream、ifstream、ofstream、seekg、seekp、tellg、tellp用法)[通俗易懂]

C++读写文件操作(fstream、ifstream、ofstream、seekg、seekp、tellg、tellp用法)[通俗易懂]

作者头像
全栈程序员站长
发布2022-09-03 13:45:47
发布2022-09-03 13:45:47
9.9K0
举报

大家好,又见面了,我是你们的朋友全栈君。

本文主要总结用C++的fstream、ifstream、ofstream方法读写文件,然后用seekg()、seekp()函数定位输入、输出文件指针位置,用tellg()、tellp()获取当前文件指针位置。

一、核心类和函数功能讲解

fstream:文件输入输出类。表示文件级输入输出流(字节流);

ifstream:文件输入类。表示从文件内容输入,也就是读文件;

ofstream:文件输出类。表示文件输出流,即文件写。

seekg():输入文件指针跳转函数。表示将输入文件指针跳转到指定字节位置‘

seekp():输出文件指针跳转函数。表示将输出文件指针跳转到指定位置。

下面将通过总结一个读写*.txt文件来演示上述输入输出类和文件跳转函数用法。

二、简单示例

2.1源代码

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdio>

struct planet
{
	char name[20];
	double population;
	double g;
}p1;

int main()
{
	using namespace std;

	/*读文件*/
	int ct = 0;		//计数
	fstream finout;	//文件读和写字节流
	finout.open("test1.txt", ios_base::in | ios_base::out | ios_base::binary);	//二进制读和写
	if (!finout.is_open())
	{
		cout << "open file E:\\1TJQ\\test1.txt fail!";
		system("pause");
		return false;
	}
	finout.seekg(0);	//输入流文件跳转指针,回到文件起始位置
	cout << "show red file\n";
	while (finout.read((char *) &p1,sizeof p1))
	{
		cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;
	}
	if (finout.eof())
		finout.clear();	//清空结尾eof标志,可以再次打开该文件



	/*写文件*/
	streampos place = 3 * sizeof p1;	//转换到streampos类型
	finout.seekg(place);	//随机访问
	if (finout.fail())
	{
		cerr << "error on attempted seek\n";
		system("pause");
		exit(EXIT_FAILURE);
	}

	finout.read((char *)&p1, sizeof p1);
	cout << "\n\nshow writed file\n";
	cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;
	if (finout.eof())
		finout.clear();	//清楚eof标志

	memcpy(p1.name, "Name1", sizeof("Name1"));	 
	p1.population = 66.0;
	p1.g == 55.0;
	finout.seekp(place);
	finout.write((char *)&p1, sizeof p1) << flush;
	if (finout.fail())
	{
		cerr << "error attempted write\n";
		system("pause");
		exit(EXIT_FAILURE);
	}



	/*显示修改后的文件内容*/
	ct = 0;
	finout.seekg(0);
	cout << "\n\nshow revised file\n";
	while (finout.read((char *) &p1,sizeof p1))
	{		
		cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;
	}

	system("pause");
	return 0;
}

2.2输出结果如下图所示

参考内容:

《C++ Primer Plus》(第6版)中文版 773-787页(参考:文件模式)

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/139917.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、核心类和函数功能讲解
  • 二、简单示例
    • 2.1源代码
    • 2.2输出结果如下图所示
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档