文件流的定位

这里写目录标题

  • seekg
    • tellg
      • seekp

seekg

seekg( off_type offset, //偏移量
ios::seekdir origin ); //起始位置
作用:设置输入流的位置
参数1: 偏移量
参数2: 相对位置
beg 相对于开始位置
cur 相对于当前位置
end 相对于结束位置

#include 
#include 
#include 

using namespace std;

int main(void) {
     
	ifstream infile;

	infile.open("定位.cpp");
	if (!infile.is_open()) {
     
		return 1;
	}

	infile.seekg(-50, infile.end);
	while (!infile.eof()) {
     
		string line;
		getline(infile, line);
		cout << line << endl;
	}

	infile.close();

	system("pause");
	return 0;
}

tellg

返回该输入流的当前位置(距离文件的起始位置的偏移量)

获取当前文件的长度

#include 
#include 
#include 

using namespace std;

int main(void) {
     
	ifstream infile;

	infile.open("定位.cpp");
	if (!infile.is_open()) {
     
		return 1;
	}

	// 先把文件指针移动到文件尾
	infile.seekg(0, infile.end);

	int len = infile.tellg();
	cout << "len:" << len;

	infile.close();
	system("pause");
	return 0;
}

seekp

设置该输出流的位置

demo
先向新文件写入:“123456789”
然后再在第4个字符位置写入“ABC”

#include 
#include 
#include 

using namespace std;

int main(void) {
     
	ofstream outfile;

	outfile.open("test.txt");
	if (!outfile.is_open()) {
     
		return 1;
	}

	outfile << "123456789";

	outfile.seekp(4, outfile.beg);
	outfile << "ABC";

	outfile.close();
	system("pause");
	return 0;
}

文件流的定位_第1张图片

你可能感兴趣的:(笔记,C++,c++,定位)