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.
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有