tellg详解

发布时间:2023-05-20

一、tell过去式

tell是一个C++中的流函数,在文件的读取和写入中使用较为频繁。而tellg则是一个成员函数,其返回当前读指针在读文件流中的位置,同时它还可以被用来移动文件读指针到文件流的任意位置。对于tellg可以进行以下简单的使用。

ifstream input_file("read.txt");
input_file.seekg(0, ios::beg);
cout << "The position of get pointer before reading is: " << input_file.tellg() << endl;
getline(input_file, read_buffer);
cout << "The position of get pointer after reading is: " << input_file.tellg() << endl;

这段代码中,我们打开了一个名为read.txt的文件并设置读取指针的开始位置为文件开头,紧接着我们使用了getline函数读入了文件的一行,其中读取指针的当前位置通过tellg函数得到并打印。

二、tell过去式过去分词

除了我们熟知的tellg之外,还有两个和它类似的成员函数:tellp和tellb,它们分别返回写指针和读写指针在文件流中的位置,这里不再赘述。此处我们注意区分一下它们过去式的形式:

  • tellg的过去式为toldg
  • tellp的过去式为toldp
  • tellb的过去式为toldb 这样设计的目的是让读者在代码中区分开不同类型的指针函数。

三、tell过去分词

tell函数的过去分词为told,它指的是文件流当前的位置,不依赖与读指针和写指针,因此也不需要使用到输入输出流的操作符。使用told时我们需要打开二进制文件,并使用ifstream和ofstream的read和write函数来进行文件流的IO操作。

char write_buffer[100];
ifstream read_file("read.txt");
read_file.seekg(0, ios::beg);
ofstream write_file("write.bin", ios::binary | ios::out );
int file_size = 0;
read_file.read(write_buffer, 100);
while(!read_file.eof())
{
    file_size += read_file.gcount();
    write_file.write(write_buffer, read_file.gcount());
    read_file.read(write_buffer, 100);
}
cout << "File size is: " << file_size << endl;
read_file.close();
write_file.close();

这段代码中,我们打开名为read.txt的文件,并设置读指针为其开始位置。我们然后通过write函数给名为write.bin的文件写入这100个字节的数据,随后我们使用gcount函数找出实际读入到read_buffer中的字符数,并将文件的大小设置为file_size。在循环结束后关闭文件读写流。

四、tell过去+

tellg过去+是telling,它指的是读操作完成后,读取指针的位置。telling的用法和toldg大同小异:

ifstream input_file("read.txt");
input_file.seekg(0, ios::beg);
cout << input_file.rdbuf();
cout << "The position of get pointer after reading is: " << input_file.tellg() << endl;
cout << "The position of get pointer after reading is: " << input_file.telling() << endl;

这段代码中,我们通过rdbuf函数将文件全部读进内存中,此时读指针会自动到达文件结尾,我们紧接着输出读取指针的位置,并使用telling函数输出读取指针的位置。注意在输出完rdbuf之后,reading的位置并不是文件的末尾,因为我们读取了文件中的全部内容。

五、tell官网

tellg的详细描述可以在C++官网上找到,网址为:
https://zh.cppreference.com/w/cpp/io/basic_istream/tellg

六、tell改一个字母变成另一个词

如果我们将tell中l的位置从g后移一个字母,得到tellh,它其实并没有什么特殊的意义。同时,这个单词在搜索引擎中一般被误认为是tellg。

七、tell官方下载

由于tellg是C标准库函数之一,因此并不存在所谓的官方可供下载的版本,相关的库文件已经和C编译器捆绑在一起。如果你正在使用的编译器是Visual Studio或者CodeBlocks,那么你已经拥有了tellg的使用权限。

八、tell过分

tellg是一个非常基础的C++函数,我们在读写文件流的时候总是会用到它。因此,我们建议读者多多利用官方文档和相关参考资料来理解tellg在文件流读取中的作用和用法,掌握好文件读写流的操作。