C++ seekg函数用法案例详解

C++ seekg函数用法详解

很多时候用户可能会这样操作,打开一个文件,处理其中的所有数据,然后将文件倒回到开头,再次对它进行处理,但是这可能有点不同。例如,用户可能会要求程序在数据库中搜索某种类型的所有记录,当这些记录被找到时,用户又可能希望在数据库中搜索其他类型的所有记录。

文件流类提供了许多不同的成员函数,可以用来在文件中移动。其中的一个方法如下:

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 dogsgrowl, bark, and eat.All good dogsgrowl, bark, and eat.

到此这篇关于C++ seekg函数用法案例详解的文章就介绍到这了,更多相关C++ seekg函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

人若软弱就是自己最大的敌人

C++ seekg函数用法案例详解

相关文章:

你感兴趣的文章:

标签云: