对输入流操作:seekg()与tellg()
对输出流操作:seekp()与tellp()
下面以输入流函数为例介绍用法:
seekg()是对输入文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址。
对于第一个参数,可以是正负数值,正的表示向后偏移,负的表示向前偏移。而第二个参数可以是:
ios::beg:表示输入流的开始位置
ios::cur:表示输入流的当前位置
ios::end:表示输入流的结束位置
tellg()函数不需要带参数,它返回当前定位指针的位置,也代表着输入流的大小。
#include <iostream>
#include <fstream>//读写操作,对打开的文件可进行读写操作
#include <string>//c++风格字符串
#include <cstring>//c风格字符串
//#include <ifstream>文件读操作,存储设备读区到内存中
//#include <ofstream>文件写操作 内存写入存储设备
using namespace std;
int main()
{
//============================================//
cout << "Hello world!" << endl;
//文件内存写到磁盘
ofstream fout("001.txt");//打开待写文件
string a="where is my future !";//cha* a="where is my future !";
if (fout.is_open())
fout<<"hello cpp.\n"<<a<<endl;//写到文件
else
cout<<"file open failed"<<endl;
fout.close();
//文件磁盘读到内存
char buffer[256];
ifstream fin("002.txt");//打开待写文件
if (! fin.is_open())
{ cout << "Error opening file"; throw 1; }
while (!fin.eof() )
{
fin.getline (buffer,100);//按行读入到buffer
cout <<"read message: "<< buffer << endl;
}
fin.close();
char *b = "nihao";
cout<<b<<"字符串的长度="<<strlen(b)<<endl;
//=========================================//
//=========================================//
//read 003.txt
//const char * filename2 = "D:\\CPP\\readwrite\\003.txt";
ifstream in ("D:\\CPP\\readwrite\\003.txt", ios::in|ios::binary|ios::ate);
if (! in.is_open())
{ cout << "Error opening file 003.txt"; throw 1; }
// get length of file:
in.seekg (0, in.end);//Set position in input sequence end
long length = in.tellg();
in.seekg (0, in.beg);//Set position in input sequence begin
// allocate memory:
char* buffer2 = new char [length];//buffer2 必须是char*
// read data as a block:
in.read (buffer2, length);
in.close();
//print content:
cout<<"size="<<length<<endl;
cout <<buffer2<<endl;
//-----write to 004.txt--------//
//const char * filename3 = "004.txt";//文件名 char*
ofstream out ("004.txt", ios::out|ios::binary|ios::ate);
if (!out.is_open())
{ cout << "Error opening file 004.txt"; throw 0; }
// write to out
out.write(buffer2, length);//buffer2 必须是char *
out.close();
// release dynamically-allocated memory
delete[] buffer2;
return 0;
}