C++ seekg函數(shù)用法案例詳解
C++ seekg函數(shù)用法詳解
很多時候用戶可能會這樣操作,打開一個文件,處理其中的所有數(shù)據(jù),然后將文件倒回到開頭,再次對它進行處理,但是這可能有點不同。例如,用戶可能會要求程序在數(shù)據(jù)庫中搜索某種類型的所有記錄,當這些記錄被找到時,用戶又可能希望在數(shù)據(jù)庫中搜索其他類型的所有記錄。
文件流類提供了許多不同的成員函數(shù),可以用來在文件中移動。其中的一個方法如下:
seekg(offset, place);
這個輸入流類的成員函數(shù)的名字 seekg 由兩部分組成。首先是 seek(尋找)到文件中的某個地方,其次是 "g" 表示 "get",指示函數(shù)在輸入流上工作,因為要從輸入流獲取數(shù)據(jù)。
要查找的文件中的新位置由兩個形參給出:新位置將從由 place 給出的起始位置開始,偏移 offset 個字節(jié)。offset 形參是一個 long 類型的整數(shù),而 place 可以是 ios 類中定義的 3 個值之一。起始位置可能是文件的開頭、文件的當前位置或文件的末尾,這些地方分別由常量 ios::beg、ios::cur 和 ios::end 表示。
有關在文件中移動的更多信息將在后面的章節(jié)中給出,目前先來關注如何移動到文件的開頭。要移到文件的開始位置,可以使用以下語句:
seekg(0L,ios::beg);
以上語句表示從文件的開頭位置開始,移動 0 字節(jié),實際上就是指移動到文件開頭。
注意,如果目前已經(jīng)在文件末尾,則在調(diào)用此函數(shù)之前,必須清除文件末尾的標志。因此,為了移動到剛讀取到末尾的文件流 dataln 的開頭,需要使用以下兩個語句:
dataIn.clear(); dataIn.seekg(0L, ios::beg);
下面的程序演示了如何倒回文件的開始位置。它首先創(chuàng)建一個文件,寫入一些文本,并關閉文件;然后打開文件進行輸入,一次讀取到最后,倒回文件開頭,然后再次讀?。?/p>
//Program shows how to rewind a file. It writes a text file and opens it for reading, then rewinds
// it to the beginning and reads it again.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Variables needed to read or write file one character at a time char ch;
fstream ioFile("rewind.txt", ios::out);
// Open file.
if (!ioFile)
{
cout << "Error in trying to create file";
return 0;
}
// Write to file and close
ioFile << "All good dogs" << endl << "growl, bark, and eat." << endl;
ioFile.close();
//Open the file
ioFile.open ("rewind.txt", ios::in);
if (!ioFile)
{
cout << "Error in trying to open file";
return 0;
}
// Read the file and echo to screen
ioFile.get(ch);
while (!ioFile.fail())
{
cout.put(ch);
ioFile.get(ch);
}
//Rewind the file
ioFile.clear();
ioFile.seekg(0, ios::beg);
//Read file again and echo to screen
ioFile.get(ch);
while (!ioFile.fail())
{
cout.put(ch);
ioFile.get(ch);
}
return 0;
}
程序輸出結果:
All good dogs
growl, bark, and eat.
All good dogs
growl, bark, and eat.
到此這篇關于C++ seekg函數(shù)用法案例詳解的文章就介紹到這了,更多相關C++ seekg函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VisualStudio2019解決scanf函數(shù)報錯問題
在 Visual Studio 2019 編輯代碼時,前期剛剛接觸到VS編譯器時存在的困惑,當用scanf()函數(shù),進行輸入時,在運行的時候編譯器會出現(xiàn)警告報錯,本文就來介紹一下解決方法2023-08-08
淺談C++函數(shù)聲明后面加throw()的作用(必看)
下面小編就為大家?guī)硪黄獪\談C++函數(shù)聲明后面加throw()的作用(必看)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
C++11 std::shared_ptr總結與使用示例代碼詳解
這篇文章主要介紹了C++11 std::shared_ptr總結與使用,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06

