在使用文件流的过程中,涉及到两个函数用来移动读写位置,分别是 seekp 和 seekg,seekp 函数用于已经打开要进行输出的文件,而 seekg 函数则用于已经打开要进行输入的文件。可以将 “p” 理解为 “put”,将 “g” 理解为 “get”,这样理解当然是有根据的,因为 seekp 可用于将信息 put(放入)到文件中,而 seekg 则可用于从文件中 get(获取)信息。
关于seekp()的函数用法如下:
seekp(20L, ios::beg);
ios::beg 从文件头开始计算偏移量
ios::end 从文件末尾开始计算偏移量
ios::cur 从当前位置开始计算偏移量
文件寻找操作:
file.seekp(32L, ios::beg); 将写入位置设置为从文件开头开始的第 33 个字节(字节 32)
file.seekp(-10L, ios::end); 将写入位置设置为从文件末尾开始的第 11 个字节(字节 10)
file.seekp(120L, ios::cur); 将写入位置设置为从当前位置开始的第 121 个字节(字节 120)
file.seekg(2L, ios::beg); 将读取位置设置为从文件开头开始的第 3 个字节(字节 2)
file.seekg(-100L, ios::end); 将读取位置设置为从文件末尾开始的第 101 个字节(字节 100)
file.seekg(40L, ios::cur); 将读取位置设置为从当前位置开始的第 41 个字节(字节 40)
file.seekg(0L, ios:rend); 将读取位置设置为文件末尾
eg:
//This program demonstrates the seekg function.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Variable to access file
char ch;
// Open the file for reading
fstream file ("letters.txt", ios::in);
if (!file)
{
cout << "Error opening file.";
return 0;
}
// Get fifth byte from beginning of alphabet file
file.seekg(5L, ios::beg);
file.get(ch);
cout << "Byte 5 from beginning: " << ch << endl;
// Get tenth byte from end of alphabet file
file.seekg(-10L, ios::end);
file.get(ch);
cout << "Byte 10 from end: " << ch << endl;
//Go forward three bytes from current position
file.seekg(3L, ios::cur);
file.get(ch);
cout << "Byte 3 from current: " << ch << endl;
// Close file
file.close ();
return 0;
}