读取文件位置 seekg()
-
seekg( off_type offset, //偏移量
ios::seekdir origin ); //起始位置 -
作用:设置输入流的位置
-
参数1: 偏移量
-
参数2: 相对位置
beg 相对于开始位置
cur 相对于当前位置
end 相对于结束位置 -
文件file相对于开始位置,往后移动10个字节
seekg(10, file.beg); -
文件file相对于尾部位置,往前移动10个字节
seekg(-10, file.end);
例: 读取文件的最后50个字符
#include <iostream>
#include <Windows.h>
#include <fstream> //读写文件流
#include <string>
using namespace std;
//需求, 读取当前文件的最后50字符
int main(void) {
string line;
ifstream file;
file.open("main.cpp", ios::in);
//从定位到文件尾部往前50个字节
file.seekg(-50, file.end);
while (!file.eof()) {
getline(file, line); //读取一行
cout << line << endl; //打印输出
}
file.close();
system("pause");
return 0;
}
读取文件大小 tellg()
- 返回该输入流的当前位置(距离文件的起始位置的偏移量)
获取当前文件的长度
#include <iostream>
#include <Windows.h>
#include <fstream> //读写文件流
#include <string>
using namespace std;
//需求, 读取当前文件的大小
int main(void) {
int len = 0;
ifstream file;
file.open("main.cpp", ios::in);
//先把文件指针定位到文件尾部
file.seekg(0, file.end);
len = file.tellg(); //获取file文件长度
cout << len << endl;
file.close();
system("pause");
return 0;
}
设置写入位置 seekp()
- 设置该输出流的位置
先向新文件写入:“123456789”
然后再在第4个字符位置写入“ABC
#include <iostream>
#include <Windows.h>
#include <fstream> //读写文件流
#include <string>
using namespace std;
//需求, 读取当前文件的大小
int main(void) {
ofstream file;
file.open("text.txt", ios::out);
//先写入123456789
file << "123456789";
//定位到第4个字符位置
file.seekp(4, file.beg);
//再往第4个位置插入ABC
file << "ABC";
file.close();
system("pause");
return 0;
}