C++文件的随机读写
2021/10/23 12:39:41
本文主要是介绍C++文件的随机读写,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目录
1.seekg
2.tellg
3.seekup
1.seekg(设置输出流位置)
.seekg(off_type offset, //偏移量
ios::seekdir orgin); //起始位置
参数1:偏移量
参数2:起始位置
bge 相对于开始位置
cur 相对于当前位置
end 相对于结束位置
#include<fstream> #include<iostream> #include<string> using namespace std; int main() { ifstream ifs; ifs. open("源.cpp"); if (!ifs.is_open()) { return 1; } ifs.seekg(-50, ifs.end); //设置输出流位置 string line; while (!ifs.eof()) { getline(ifs, line); cout << line << endl; } ifs.close(); system("pause"); return 0; }
2.tellg(返回当前流位置)
.tellg
返回该输入流当前位置
#include<fstream> #include<iostream> #include<string> using namespace std; int main() { ifstream ifs; ifs. open("源.cpp"); if (!ifs.is_open()) { return 1; } //先把文件指针移到尾部,放回当前流位置 ifs.seekg(0, ifs.end); int lenth = ifs.tellg(); cout << "文件长度为:" << lenth << endl; ifs.close(); system("pause"); return 0; }
3.seekup(设置输入流位置)
向新文件写入“12345678”,然后在第四个字符位置写入”ABC“
#include<fstream> #include<iostream> #include<string> using namespace std; int main() { ofstream ofs; ofs.open("test.txt"); if(!ofs.is_open()) { return 1; } ofs << "12345678"; ofs.seekp(4, ofs.beg); //设置输入流位置 ofs << "ABC"; ofs.close(); ifstream ifs; ifs.open("test.txt"); if (!ifs.is_open()) { return 1; } string line; getline(ifs, line); cout << line << endl; ifs.close(); system("pause"); return 0; }
这篇关于C++文件的随机读写的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享
- 2024-07-04make后如何升级ssh-icode9专业技术文章分享
- 2024-07-03微信支付提示下单账户与支付账户不一致-icode9专业技术文章分享