seekg(offset, place);
這個輸入流類的成員函數的名字 seekg 由兩部分組成。首先是 seek(尋找)到檔案中的某個地方,其次是 "g" 表示 "get",指示函數在輸入流上工作,因為要從輸入流獲取資料。seekg(0L,ios::beg);
以上語句表示從檔案的開頭位置開始,移動 0 位元組,實際上就是指移動到檔案開頭。
dataIn.clear();
dataIn.seekg(0L, ios::beg);
//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.