C++文件操作:控制文件读写位置
(2011-11-28 14:50:32)
标签:
c文件读写位置杂谈 |
分类: 技术分享 |
istream &seekg(streamoff offset,seek_dir origin);
ostream &seekp(streamoff offset,seek_dir origin);
streamoff定义于 iostream.h 中,定义有偏移量 offset 所能取得的最大值,seek_dir 表示移动的基准位置,是一个有以下值的枚举:
ios::beg: 文件开头
ios::cur: 文件当前位置
ios::end: 文件结尾
这两个函数一般用于二进制文件,因为文本文件会因为系统对字符的解释而可能与预想的值不同。
例:
file1.seekg(1234,ios::cur);//把文件的读指针从当前位置向后移1234个字节
file2.seekp(1234,ios::beg);//把文件的写指针从文件开头向后移1234个字节
下面是我第一次的程序有关写文件的操作:
string area,address;
int num;
ofstream outfile("output.txt");
outfile<<area<<"
下面是改进后的操作:
string area,address;
int num;
ofstream outfile("output.txt");
outfile<<area;
outfile.seekp(-strlen(area.c_str()) + 30,ios::cur);
outfile<<address;
outfile.seekp(-strlen(address.c_str()) + 30,ios::cur);
outfile<<num<<endl;
这里用strlen()函数就完美的解决了字符串长度参差不齐的问题。。。。
可以通过调用seekp()成员函数来指定逻辑指针到文件中的任一位置,seekp()成员函数通过指定的位置偏移量实现文件中重新定位。
在下面的范例中,程序定位到第10字节的文件位置,然后调用tellp()来输出新的位置:
fout.seekp(10); // move 10 bytes
ahead from beginning
cout<<"new
position: "<<fout.tellp(); // display
10
我在应用tellp成员函数读取文件指针时是这样用的:
ifstream infile("input.txt")
ofstream outfile("output.txt")
......
int temp=infile.tellp();
.......
infile.seekp(temp);
编译器会报错,提示tellp并不是std::ifstream的成员函数,把infile的定义类型改成fstream就行了,也就是:
fstream infile;
infile.open("input.txt");