1. seekg,tellg
Ø 功能:设置输入文件流的文件流指针位置
Ø 示例程序:
例1
// read a file into memory
#include <iostream> // std::cout
#include <fstream> // std::ifstream
int main () {
std::ifstream is ("D:/test.txt", std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);//将读取is指针移到离is.end的0处意思是将此指针移到文件末尾
int length = is.tellg();//返回输入流中的当前字符的位置。 is.seekg (0, is.beg);// 将读取is指针移到离is.beg的0处意思是将此指针移到文件开始
// allocate memory:
char * buffer = new char [length+1];
memset(buffer,0,length+1);
// read data as a block:
is.read (buffer,length);
is.close();
// print content:
std::cout.write (buffer,length);
delete[] buffer;
}
return 0;
}
2. seekp,tellp
Ø 功能:设置输出文件流的文件流指针位置
Ø 示例程序
例1
#include <fstream> // std::ofstream
int main () {
std::ofstream outfile;
outfile.open (
"D:/test.txt");
outfile.write (
"This is an apple",16);
long
pos = outfile.tellp();//返回当前文件指针的位置
outfile.
seekp(pos-7);
outfile.write (
" sam",4);
outfile.close();
return
0;
}