当前位置: 首页 > news >正文

C++文件操作

文件打开模式:

ios::in:读取模式
ios::out:写入模式
ios::app:追加模式
ios::binary:二进制模式
ios::ate:文件打开后定位到文件末尾
ios::trunc:如果文件存在,删除文件内容

一、常规内容写入

// 写入文件文件 #include<iostream> #include<fstream>// 包含文件操作所需的头文件 using namespace std; int main() { // 创建操作对象 const string filePath = R"(D:\fileReadTest.txt)"; ofstream file(filePath,ios::out);// 以写入模式操作文件 // 判断文件是否正常打开 if(!file.is_open()){ cout<<"Error!the file is not open!"<<endl; return -1; } // 文件正常打开,进行后续操作 // 写入内容 file<<"开始写入"<<endl; file<<"This is the second line."<<endl; file<<"This is the third line."<<endl; file<<"写入完毕"<<endl; // 务必记得关闭文件 file.close(); cout<<"end!"<<endl; return 0; }

// 读取文本文件 #include<iostream> #include<fstream>// 包含文件操作所需的头文件 using namespace std; int main() { // 创建操作对象 const string filePath = R"(D:\fileReadTest.txt)"; ifstream file(filePath,ios::out); // 判断文件是否正常打开 if(!file.is_open()){ cout<<"Error!the file is not open!"<<endl; return -1; } // 文件正常打开,进行后续操作 // 读取文件内容(逐行读取) cout<<"文件内容为:"<<endl; string text; while(getline(file,text)){ cout<<text<<endl; } // 务必记得关闭文件 file.close(); return 0; }

二、自定义内容写入

// 写入内容 #include<iostream> #include<fstream>// 包含文件操作所需的头文件 using namespace std; int main() { // 创建操作对象 const string filePath = R"(D:\fileReadTest.txt)"; ofstream file(filePath,ios::out); // 判断文件是否正常打开 if(!file.is_open()){ cout<<"Error!the file is not open!"<<endl; return -1; } // 文件正常打开,进行后续操作 string name = "zhangsan"; int age = 25; char sex = 'm'; file<<name<<" "<<age<<" "<<sex<<endl; // 务必记得关闭文件 file.close(); return 0; }
// 读取内容 #include<iostream> #include<fstream>// 包含文件操作所需的头文件 using namespace std; int main() { // 创建操作对象 const string filePath = R"(D:\fileReadTest.txt)"; ifstream file(filePath,ios::out); // 判断文件是否正常打开 if(!file.is_open()){ cout<<"Error!the file is not open!"<<endl; return -1; } // 文件正常打开,进行后续操作 file.clear(); file.seekg(0); string name; int age; char sex; while(file>>name>>age>>sex){ cout<<name<<" "<<age<<" "<<sex<<endl; } // 务必记得关闭文件 file.close(); return 0; }
http://www.jsqmd.com/news/425461/

相关文章:

  • MongoDB哈希索引实战:分布式环境下的数据均匀分布策略
  • MongoDB地理空间索引:2dsphere与2d索引的应用场景对比
  • 手撕AVL树——从失衡到平衡,彻底搞懂旋转机制
  • 空性:AI元人文
  • UNIX演进与POSIX
  • [豪の算法奇妙冒险] 代码随想录算法训练营第五十天 | 图论理论基础、深搜理论基础、Carl98-所有可达路径、广搜理论基础
  • 华为OD机考双机位C卷 - 模拟数据序列化传输 (Java Python JS GO C++ C)
  • WPF 将NET Framework项目升级到SDK风格的项目
  • 华为OD机考双机位C卷 - 矩形绘制 (Java Python JS GO C++ C)
  • 基于微信小程序的健康指导平台小程序_h8xdm24b
  • 提升汽车软件开发效率:CAN信号处理模块的自动对齐技术
  • 普通数组-----缺失的第一个正数
  • java面试速记-linux知识点
  • AI应用架构师必看:虚拟教育系统中的计算机视觉架构
  • python: Chain of Responsibility Pattern
  • 题解:P15546 「Stoi2037」七里香
  • 每日督促
  • 随笔 7
  • 2026.3.1省选模拟赛
  • Seal Plus 2.2.0 | 开源视频下载器,支持1000+视频平台
  • 彼得林奇的“质量成长“vs“价值陷阱“
  • 多智能体系统如何评估公司的长期盈利能力
  • Musify 9.8.4 | 纯净无广免费音乐软件, 畅听国内外歌曲, 需要特殊网络
  • 虚拟展厅AI训练数据从哪来?架构师设计高效数据标注平台实践
  • 全面了解:提示工程师职业认证体系,提示工程架构师的职业指南书
  • AI原生应用领域联邦学习的性能评估指标
  • PowerShell 新建 SharePoint Online 列表
  • 基于springboot框架的火车票购票系统_33bx0nk0
  • 基于springboot框架的航班查询与推荐系统飞机订票系统设计与开发_d1b11p63
  • 有源电力滤波器Matlab仿真之旅