seekg()與tellg()相關文件操作

對輸入流操作:seekg()與tellg()
對輸出流操作:seekp()與tellp()
下面以輸入流函數爲例介紹用法:
seekg()是對輸入文件定位,它有兩個參數:第一個參數是偏移量,第二個參數是基地址。
對於第一個參數,可以是正負數值,正的表示向後偏移,負的表示向前偏移。而第二個參數可以是:
ios::beg:表示輸入流的開始位置
ios::cur:表示輸入流的當前位置
ios::end:表示輸入流的結束位置
tellg()函數不需要帶參數,它返回當前定位指針的位置,也代表着輸入流的大小。

假設文件test。txt爲以下內容:
hello,my world
name:hehonghua
date:20090902

程序爲:

#include <iostream>
#include <fstream>
#include <assert.h>

using namespace std;
int main()
{
    ifstream in("test.txt");
    assert(in);

    in.seekg(0,ios::end);       //基地址爲文件結束處,偏移地址爲0,於是指針定位在文件結束處
    streampos sp=in.tellg(); //sp爲定位指針,因爲它在文件結束處,所以也就是文件的大小
    cout<<"file size:"<<endl<<sp<<endl;

    in.seekg(-sp/3,ios::end); //基地址爲文件末,偏移地址爲負,於是向前移動sp/3個字節
    streampos sp2=in.tellg();
    cout<<"from file to point:"<<endl<<sp2<<endl;

    in.seekg(0,ios::beg);        //基地址爲文件頭,偏移量爲0,於是定位在文件頭
    cout<<in.rdbuf();             //從頭讀出文件內容
    in.seekg(sp2);

    cout<<in.rdbuf()<<endl; //從sp2開始讀出文件內容

    return 0;
}

則結果輸出:
file size:
45
from file to point:
30
hello,my world
name:hehonghua
date:20090902

date:20090902

int main()
{
 //得到文件大小:C++方式
 ifstream ifs;
 ifs.open("log.txt");
 assert(ifs.is_open());
 ifs.seekg( 0 , std::ios::end );
 cout<<ifs.tellg()<<endl;
 ifs.close();

 // 得到文件大小:C方式
 FILE* fp = fopen("log.txt", "rb");
 assert ( 0 == fseek(fp, 0, SEEK_END));
 unsigned int usize = ftell(fp);
 cout<<usize<<endl;
 fclose(fp);

 return 0;
}
發佈了98 篇原創文章 · 獲贊 68 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章