C++文件的随机读写

目录

 1.seekg

 2.tellg

 3.seekup


 

 1.seekg(设置输出流位置)

.seekg(off_type offset,   //偏移量

            ios::seekdir orgin);    //起始位置

参数1:偏移量

参数2:起始位置

        bge        相对于开始位置

        cur        相对于当前位置

        end        相对于结束位置

#include<fstream>
#include<iostream>
#include<string>
using namespace std;

int main() {
	ifstream ifs;
	ifs. open("源.cpp");
	if (!ifs.is_open()) {
		return 1;
	}
	ifs.seekg(-50, ifs.end);  //设置输出流位置
	string line;
	while (!ifs.eof()) {
		getline(ifs, line);
		cout << line << endl;
	}
	ifs.close();
	system("pause");
	return 0;

}

 2.tellg(返回当前流位置)

 .tellg

返回该输入流当前位置

#include<fstream>
#include<iostream>
#include<string>
using namespace std;

int main() {
	ifstream ifs;
	ifs. open("源.cpp");
	if (!ifs.is_open()) {
		return 1;
	}

	//先把文件指针移到尾部,放回当前流位置
	ifs.seekg(0, ifs.end);

	int lenth = ifs.tellg();
	cout << "文件长度为:" << lenth << endl;
	ifs.close();
	system("pause");
	return 0;

}

 3.seekup(设置输入流位置)

向新文件写入“12345678”,然后在第四个字符位置写入”ABC“

#include<fstream>
#include<iostream>
#include<string>
using namespace std;

int main() {
	ofstream ofs;
	ofs.open("test.txt");
	if(!ofs.is_open()) { return 1; }
	ofs << "12345678";
	ofs.seekp(4, ofs.beg);           //设置输入流位置
	ofs << "ABC";
	ofs.close();

	ifstream ifs;
	ifs.open("test.txt");
	if (!ifs.is_open()) { return 1; }
	string line;
	getline(ifs, line);
	cout << line << endl;
	ifs.close();
	system("pause");
	return 0;

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值