C++文件的随机读写

2021/10/23 12:39:41

本文主要是介绍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;

}

 

 

 



这篇关于C++文件的随机读写的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程