
文件流类提供了许多不同的成员函数,可以用来在文件中移动。其中的一个方法如下:
seekg(offset,place);
这个输入流类的成员函数的名字 seekg 由两部分组成。首先是 seek(寻找)到文件中的某个地方,其次是 "g" 表示 "get",指示函数在输入流上工作,因为要从输入流获取数据。要查找的文件中的新位置由两个形参给出:新位置将从由 place 给出的起始位置开始,偏移 offset 个字节。offset 形参是一个 long 类型的整数,而 place 可以是 ios 类中定义的 3 个值之一。起始位置可能是文件的开头、文件的当前位置或文件的末尾,这些地方分别由常量 ios::beg、ios::cur 和 ios::end 表示。
有关在文件中移动的更多信息将在后面的章节中给出,目前先来关注如何移动到文件的开头。要移到文件的开始位置,可以使用以下语句:
seekg(0L,ios::beg);
以上语句表示从文件的开头位置开始,移动 0 字节,实际上就是指移动到文件开头。注意,如果目前已经在文件末尾,则在调用此函数之前,必须清除文件末尾的标志。因此,为了移动到刚读取到末尾的文件流 dataln 的开头,需要使用以下两个语句:
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,and eat.
All good dogs
growl,and eat.
以上是内存溢出为你收集整理的C++ seekg函数用法详解全部内容,希望文章能够帮你解决C++ seekg函数用法详解所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)