南昌加盟网站建设,唯品会网站架构,网址大全电脑版,邯郸市中心医院本专栏记录C学习过程包括C基础以及数据结构和算法#xff0c;其中第一部分计划时间一个月#xff0c;主要跟着黑马视频教程#xff0c;学习路线如下#xff0c;不定时更新#xff0c;欢迎关注。 当前章节处于#xff1a; ---------第1阶段-C基础入门 ---------第2阶段实战… 本专栏记录C学习过程包括C基础以及数据结构和算法其中第一部分计划时间一个月主要跟着黑马视频教程学习路线如下不定时更新欢迎关注。 当前章节处于 ---------第1阶段-C基础入门 ---------第2阶段实战-通讯录管理系统 第3阶段-C核心编程 ---------第4阶段实战-基于多态的企业职工系统 ---------第5阶段-C提高编程 ---------第6阶段实战-基于STL泛化编程的演讲比赛 ---------第7阶段-C实战项目机房预约管理系统 文章目录 1. 概述2. 写文件3. 读文件3. 二进制写文件4. 以二进制形式读文件 1. 概述
程序运行时产生的数据都属于临时数据程序一旦运行结束都会被释放通过文件的方式可以将数据持久化C中对文件操作需要包含头文件fstream 文件类型分为两种
文本文件 - 文件以文本的ASCII码形式存储在计算集中二进制文件 - 文件以文本的二进制形式存储在计算机中用户一般不能直接读懂他们
操作文件的三大类
ofstream:写操作ifstream读操作fstrean读写操作
2. 写文件
写文件的步骤
包含头文件 # include fstream创建流对象 ofstream ofs;打开文件 ofs.open(“文件路径”打开方式写数据 ofs“写入的数据”;关闭文件 ofs.close() 打开方式可以配合使用用 | 操作符
#include iostream
using namespace std;
# include fstream;int main() {fstream ofs;ofs.open(test.txt, ios::out); // 如果不存在会先创建ofs Hello World endl;ofs.close();system(pause);return 0;}test.txt
Hello World3. 读文件
读文件与写文件步骤相似但是读取方式相对比较多 步骤如下
包含头文件 # include fstream创建流对象 ifstream ifs;打开文件并判断文件是否打开成功 ifs.open(“文件路径”,打开方式);读数据 四种方式读取关闭文件 ifs.close();
#include iostream
# include fstreamusing namespace std;
# include string
int main() {ifstream ifs;ifs.open(test.txt, ios::in);// 读文件 方法一//char buf[1024] { 0 };//while (ifs buf) {// cout buf endl;//}// 方法二//char buf[1024] { 0 };//while (ifs.getline(buf,1024)) {// cout buf endl;//}// 方法三 //string buf;//while (getline(ifs,buf)) {// cout buf endl;//}char c;while ((cifs.get())!EOF) {cout c;}system(pause);return 0;}Hello World
张三
李四
12345请按任意键继续. . .3. 二进制写文件
#include iostream
using namespace std;
#include fstream
class Person {
public:char name[64];int age;
};int main() {ofstream ofs;ofs.open(Person.txt,ios::out|ios::binary);Person p {张三,17};// 以二进制形式写文件ofs.write((const char*)p, sizeof(p));ofs.close();cout 写入完成 endl;system(pause);return 0;}写入完成
请按任意键继续. . .4. 以二进制形式读文件
#include iostream
using namespace std;
#include fstream
class Person {
public:char name[64];int age;
};int main() {ifstream ifs;ifs.open(Person.txt, ios::out | ios::binary);// 以二进制形式写文件Person p;ifs.read((char*)p, sizeof(p));cout 读入完成 endl;cout 姓名 p.name 年龄 p.age endl;ifs.close();system(pause);return 0;}读入完成
姓名张三 年龄17
请按任意键继续. . .