100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > C++读写文件操作(fstream ifstream ofstream seekg seekp tellg tellp用法)

C++读写文件操作(fstream ifstream ofstream seekg seekp tellg tellp用法)

时间:2020-08-31 07:26:57

相关推荐

C++读写文件操作(fstream ifstream ofstream seekg seekp tellg tellp用法)

本文主要总结用C++的fstream、ifstream、ofstream方法读写文件,然后用seekg()、seekp()函数定位输入、输出文件指针位置,用tellg()、tellp()获取当前文件指针位置。

一、核心类和函数功能讲解

fstream:文件输入输出类。表示文件级输入输出流(字节流);

ifstream:文件输入类。表示从文件内容输入,也就是读文件;

ofstream:文件输出类。表示文件输出流,即文件写。

seekg():输入文件指针跳转函数。表示将输入文件指针跳转到指定字节位置‘

seekp():输出文件指针跳转函数。表示将输出文件指针跳转到指定位置。

下面将通过总结一个读写*.txt文件来演示上述输入输出类和文件跳转函数用法。

二、简单示例

2.1源代码

#include <iostream>#include <fstream>#include <iomanip>#include <cstdio>struct planet{char name[20];double population;double g;}p1;int main(){using namespace std;/*读文件*/int ct = 0;//计数fstream finout;//文件读和写字节流finout.open("test1.txt", ios_base::in | ios_base::out | ios_base::binary);//二进制读和写if (!finout.is_open()){cout << "open file E:\\1TJQ\\test1.txt fail!";system("pause");return false;}finout.seekg(0);//输入流文件跳转指针,回到文件起始位置cout << "show red file\n";while (finout.read((char *) &p1,sizeof p1)){cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;}if (finout.eof())finout.clear();//清空结尾eof标志,可以再次打开该文件/*写文件*/streampos place = 3 * sizeof p1;//转换到streampos类型finout.seekg(place);//随机访问if (finout.fail()){cerr << "error on attempted seek\n";system("pause");exit(EXIT_FAILURE);}finout.read((char *)&p1, sizeof p1);cout << "\n\nshow writed file\n";cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;if (finout.eof())finout.clear();//清楚eof标志memcpy(p1.name, "Name1", sizeof("Name1")); p1.population = 66.0;p1.g == 55.0;finout.seekp(place);finout.write((char *)&p1, sizeof p1) << flush;if (finout.fail()){cerr << "error attempted write\n";system("pause");exit(EXIT_FAILURE);}/*显示修改后的文件内容*/ct = 0;finout.seekg(0);cout << "\n\nshow revised file\n";while (finout.read((char *) &p1,sizeof p1)){cout << ct++ << " " << p1.name << " " << p1.population << " " << p1.g << endl;}system("pause");return 0;}

2.2输出结果如下图所示

参考内容:

《C++ Primer Plus》(第6版)中文版 773-787页(参考:文件模式)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。