skeeg()和tellg()函数:
对输入流操作:seekg()与tellg()
对输出流操作:seekp()与tellp()
函数原型:
ostream& seekp( streampos pos );
ostream& seekp( streamoff off, ios::seek_dir dir);
istream& seekg( streampos pos );
istream& seekg( streamoff off, ios::seek_dir dir);
函数参数
pos:新的文件流指针位置值
off:需要偏移的值
dir:搜索的起始位置
dir参数用于对文件流指针的定位操作上,代表搜索的起始位置
下面以输入流函数为例介绍用法:
seekg()是对输入文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址。
对于第一个参数,可以是正负数值,正的表示向后偏移,负的表示向前偏移。而第二个参数可以是:
ios::beg:表示输入流的开始位置
ios::cur:表示输入流的当前位置
ios::end:表示输入流的结束位置
tellg()函数不需要带参数,它返回当前定位指针的位置,也代表着输入流的大小。
#include <iostream>
#include <fstream>
using namespace std;
struct staff
{
int num;
char name[20];
int age;
double pay;
};
int main()
{
staff staf[7] = {2101, "Li", 34, 1203, 2104, "Wang", 23, 674.5, 2108, "Fun", 54, 778,
3006, "Xue", 45, 476.5, 5101, "Ling", 39, 656.6
}, staf1;
fstream iofile("staff.dat", ios::in | ios::out | ios::binary);
if (!iofile)
{
cerr << "open error!" << endl;
return -1;
}
int i, m, num;
cout << "Five staff :" << endl;
for (i = 0; i < 5; i++)
{
cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " "
<< staf[i].pay << endl;
iofile.write((char*)&staf[i], sizeof(staf[i]));
}
cout << "please input data you want insert:" << endl;
for (i = 0; i < 2; i++)
{
cin >> staf1.num >> staf1.name >> staf1.age >> staf1.pay;
iofile.seekp(0, ios::end);
iofile.write((char*)&staf1, sizeof(staf1));
}
iofile.seekg(0, ios::beg);
for (i = 0; i < 7; i++)
{
iofile.read((char*)&staf[i], sizeof(staf[i]));
cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " "
<< staf[i].pay << endl;
}
bool find;
cout << "enter number you want search,enter 0 to stop.";
cin >> num;
while (num)
{
find = false;
iofile.seekg(0, ios::beg);
for (i = 0; i < 7; i++)
{
iofile.read((char*)&staf[i], sizeof(staf[i]));
if (num == staf[i].num)
{
m = iofile.tellg();
cout << num << " is No." << m / sizeof(staf1) << endl;
cout << staf[i].num << " " << staf[i].name << " " << staf[i].age << " "
<< staf[i].pay << endl;
find = true;
break;
}
}
if (!find)
cout << "can't find " << num << endl;
cout << "enter number you want search,enter 0 to stop.";
cin >> num;
}
iofile.close();
return 0;
}