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

C++文件的读取和写入

1、C++对txt文件的读,ios::in

#include<iostream>
#include<fstream>
using namespace std;int main()
{ifstream ifs;ifs.open("test.txt",ios::in);if(!ifs.is_open()){cout<<"打开文件失败!"<<endl;}char buff[1024] ={0};while(ifs>>buff){cout<<buff<<endl;}return 0;
}

2、c++对txt文件的写文件,ios::out

#include<iostream>
#include<fstream>
using namespace std;
int main()
{ofstream ofs;ofs.open("test1.txt",ios::out);ofs<<"岗位:LISI"<<endl<<"年龄:19"<<endl<<"xingbie:男"<<endl;ofs.close();return 0;
}

3、c++对txt文件的写文件,追加到目前文件的最后,ios::app

#include<iostream>
#include<fstream>
using namespace std;
int main()
{ofstream ofs;ofs.open("test1.txt",ios::app);ofs<<"岗位:LISI"<<endl<<"年龄:19"<<endl<<"xingbie:男"<<endl;ofs.close();return 0;
}

4、c++读取二进制文件,ios::in|ios::binary

#include<iostream>
using namespace std;
#include<fstream>
class CStudent
{public:char name[100];int age;
};int main()
{CStudent cs;ifstream infile("student.dat",ios::in|ios::binary);if(!infile)cout<<"error"<<endl;while(infile.read((char*)&cs,sizeof(cs))){int readBytes=infile.gcount();cout<<cs.name<<cs.age<<endl;}infile.close();return 0;
}

5、c++写二进制文件,ios::out|ios::binary

#include<iostream>
#include<fstream>
using namespace std;class CStudent
{public:char name[100];int age;
};int main()
{CStudent cs;ofstream outfile("student.dat",ios::out|ios::binary);while(cin>>cs.name>>cs.age)outfile.write((char*)&cs,sizeof(cs));outfile.close();return 0;
}
http://www.lryc.cn/news/228452.html

相关文章:

  • 住宅IP、家庭宽带IP以及原生IP,它们有什么区别?谷歌开发者账号应选择哪种IP?
  • Linux内核分析(十三)--内存管理之I/O交换与性能调优
  • 前端使用webscoket
  • centos安装Git
  • 网络编程 初探windows编程
  • Vue3 ref函数和reactive函数
  • docker常用命令详解
  • 采集Prestashop独立站采集Prestashop独立站
  • 2023.11-9 hive数据仓库,概念,架构,元数据管理模式
  • MFC 简单绘图与文本编辑
  • C# 中的 SerialPort
  • 2022年06月 Python(五级)真题解析#中国电子学会#全国青少年软件编程等级考试
  • YOLO图像识别
  • 2023NewStarCTF
  • 计算机网络的发展及应用
  • K-means(K-均值)算法
  • 网络安全自学
  • 加速mvn下载seatunnel相关jar包
  • 【函数讲解】botorch中的函数 is_non_dominated():用于计算非支配(non-dominated)前沿
  • LeetCode题94,44,145,二叉树的前中后序遍历,非递归
  • Python 框架学习 Django篇 (九) 产品发布、服务部署
  • Git 服务器上的 LFS 下载
  • Canvas和SVG:你应该选择哪一个?
  • openGauss学习笔记-122 openGauss 数据库管理-设置密态等值查询-密态支持函数/存储过程
  • BEVFormer 论文阅读
  • Centos批量删除系统重复进程
  • VUE组件的生命周期
  • 【Git系列】Github指令搜索
  • 【OpenCV】用数组给Mat图像赋值,单/双/三通道 Mat赋值
  • Doris:读取Doris数据的N种方法