资源网站免费的,企业官网有哪些网站,网站登录到wordpress,wordpress 4.5 中文版声明#xff1a;我个人特别讨厌#xff1a;收费专栏、关注博主才可阅读等行为#xff0c;推崇知识自由分享#xff0c;推崇开源精神#xff0c;呼吁你一起加入#xff0c;大家共同成长进步#xff01; 在文件读写的时候#xff0c;一般需要借助fstream来进行文件操作我个人特别讨厌收费专栏、关注博主才可阅读等行为推崇知识自由分享推崇开源精神呼吁你一起加入大家共同成长进步 在文件读写的时候一般需要借助fstream来进行文件操作常见的操作有seekg()和tellg()但是这两个函数有一些需要注意的地方如下 主要参考 https://stackoverflow.com/questions/20506771/get-file-size-with-ifstreamseekg-and-tellg https://stackoverflow.com/questions/28823258/which-of-these-if-the-correct-way-to-use-seekg https://stackoverflow.com/questions/11714973/istream-seekg-offsets-and-iosend 定义参考cppreference seekg: Sets input position indicator of the current associated streambuf object.中文的意思是设置当前关联streambuf对象的输入位置指示器 tellg: Returns input position indicator of the current associated streambuf object.中文的意思是返回当前关联streambuf对象的输入位置指示器
首先准备一个test.txt每行15个字符共45个字符
ssssssssssssss
aaaaaaaaaaaaaa
dddddddddddddd测试程序
#include iostream
#include fstream
using namespace std;int main() {int size 0;std::string fileName ../test.txt;ifstream in(fileName.c_str(), ifstream::in | ifstream::binary);if(in){in.seekg(0,ifstream::end);size in.tellg();cout ********** size stream1*** size endl; // ********** size stream1*** 44in.seekg(0,ios::end);size in.tellg();cout ********** size stream2*** size endl; // ********** size stream2*** 44in.seekg(ios::end);size in.tellg();cout ********** size stream3*** size endl; // ********** size stream3*** 2in.seekg(10,ios::end);size in.tellg();cout ********** size stream4*** size endl; // ********** size stream4*** 54in.seekg(-10,ios::end);size in.tellg();cout ********** size stream5*** size endl; // ********** size stream5*** 34in.seekg(0,ios::beg);size in.tellg();cout ********** size stream6*** size endl; // ********** size stream6*** 0in.seekg(ios::beg);size in.tellg();cout ********** size stream7*** size endl; // ********** size stream7*** 0in.seekg(14);in.seekg(0, ios::end);size in.tellg();cout ********** size stream8*** size endl; // ********** size stream8*** 44in.seekg(10);in.seekg(0, ios::cur);size in.tellg();cout ********** size stream9*** size endl; // ********** size stream9*** 10in.seekg(ios::beg,ios::end);size in.tellg();cout ********** size stream10*** size endl; // ********** size stream10*** 44in.seekg(ios::beg);in.seekg(ios::end);size in.tellg();cout ********** size stream11*** size endl; // ********** size stream11*** 2in.seekg(ios::cur);size in.tellg();cout ********** size stream12*** size endl; // ********** size stream12*** 1}
}代码分析
seekg()用来设置stream的文件指针位置如in.seekg(14)就是将文件指针设置到14位置处相对begin位置这里相当于in.seekg(14, ios::beg)但是对于in.seekg(ios::end)却截然不同如stream3输出为2这是因为enum seekdir {beg, cur, end}所以当使用ios::cur和ios::end且只有一个参数的时候会将ios::cur隐式转换为1ios::end隐式转换为2所以stream3输出2stream12输出1这告诉我们当使用beg, cur, end为了避免错误请使用两个参数如in.seekg(0,ios::end)代替in.seekg(ios::end)tellg()没啥好说的就是返回文件流指针所在位置 声明我个人特别讨厌收费专栏、关注博主才可阅读等行为推崇知识自由分享推崇开源精神呼吁你一起加入大家共同成长进步