轉(zhuǎn)載至http://c.biancheng.net/view/1537.html
很多時候用戶可能會這樣操作慈缔,打開一個文件嘀趟,處理其中的所有數(shù)據(jù),然后將文件倒回到開頭,再次對它進行處理谴古,但是這可能有點不同牺蹄。例如惨远,用戶可能會要求程序在數(shù)據(jù)庫中搜索某種類型的所有記錄躯枢,當(dāng)這些記錄被找到時,用戶又可能希望在數(shù)據(jù)庫中搜索其他類型的所有記錄司忱。
提供了許多不同的成員函數(shù)皇忿,可以用來在文件中移動。其中的一個方法如下:
seekg(offset, place);
這個輸入流類的成員函數(shù)的名字 seekg 由兩部分組成坦仍。首先是 seek(尋找)到文件中的某個地方鳍烁,其次是 "g" 表示 "get",指示函數(shù)在輸入流上工作繁扎,因為要從輸入流獲取數(shù)據(jù)老翘。
要查找的文件中的新位置由兩個形參給出:新位置將從由 place 給出的起始位置開始,偏移 offset 個字節(jié)锻离。offset 形參是一個 long 類型的整數(shù),而 place 可以是 ios 類中定義的 3 個值之一墓怀。起始位置可能是文件的開頭汽纠、文件的當(dāng)前位置或文件的末尾,這些地方分別由常量 ios::beg傀履、ios::cur 和 ios::end 表示虱朵。
有關(guān)在文件中移動的更多信息將在后面的章節(jié)中給出,目前先來關(guān)注如何移動到文件的開頭钓账。要移到文件的開始位置碴犬,可以使用以下語句:
seekg(0L,ios::beg);
以上語句表示從文件的開頭位置開始,移動 0 字節(jié)梆暮,實際上就是指移動到文件開頭服协。
注意,如果目前已經(jīng)在文件末尾啦粹,則在調(diào)用此函數(shù)之前偿荷,必須清除文件末尾的標(biāo)志窘游。因此,為了移動到剛讀取到末尾的文件流 dataln 的開頭跳纳,需要使用以下兩個語句:
dataIn.clear();
dataIn.seekg(0L, ios::beg);
下面的程序演示了如何倒回文件的開始位置忍饰。它首先創(chuàng)建一個文件,寫入一些文本寺庄,并關(guān)閉文件艾蓝;然后打開文件進行輸入,一次讀取到最后斗塘,倒回文件開頭赢织,然后再次讀取:
<pre class="cpp sh_cpp snippet-formatted sh_sourceCode">
1. //Program shows how to rewind a file. It writes a text file and opens it for reading, then rewinds
2. // it to the beginning and reads it again.
3. #include <iostream>
4. #include <fstream>
5. u[sin](http://c.biancheng.net/ref/sin.html)g namespace std;
7. int main()
8. {
9. // Variables needed to read or write file one character at a time char ch;
10. fstream ioFile("rewind.txt", ios::out);
11. // Open file.
12. if (!ioFile)
13. {
14. cout << "Error in trying to create file";
15. return 0;
16. }
17. // Write to file and close
18. ioFile << "All good dogs" << endl << "growl, bark, and eat." << endl;
19. ioFile.close();
20. //Open the file
21. ioFile.open ("rewind.txt", ios::in);
22. if (!ioFile)
23. {
24. cout << "Error in trying to open file";
25. return 0;
26. }
27. // Read the file and echo to screen
28. ioFile.get(ch);
29. while (!ioFile.fail())
30. {
31. cout.put(ch);
32. ioFile.get(ch);
33. }
34. //Rewind the file
35. ioFile.clear();
36. ioFile.seekg(0, ios::beg);
37. //Read file again and echo to screen
38. ioFile.get(ch);
39. while (!ioFile.fail())
40. {
41. cout.put(ch);
42. ioFile.get(ch);
43. }
44. return 0;
45. }
</pre>
程序輸出結(jié)果:
All good dogs
growl, bark, and eat.
All good dogs
growl, bark, and eat.