zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

C++文件 操作 通俗易懂 用法 读写 fstream seekg
2023-06-13 09:11:55 时间

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

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

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

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

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

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

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

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

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

二、简单示例

2.1源代码

#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