当前位置: 首页> 文旅> 文化 > 山西专业制作网站_合肥效果图制作公司_app推广方案_河南网站seo费用

山西专业制作网站_合肥效果图制作公司_app推广方案_河南网站seo费用

时间:2025/7/11 0:31:30来源:https://blog.csdn.net/QoQ_____________/article/details/142414174 浏览次数:0次
山西专业制作网站_合肥效果图制作公司_app推广方案_河南网站seo费用

文件分类


文本文件:以 ASCII码 存储

二进制文件:以 二进制 形式存储

操作文件:


1. ofstream:写操作
2. ifstream: 读操作
3. fstream : 读写操作

写文件


1. 包含头文件   

     #include <fstream>

2. 创建流对象  

   ofstream ofs;

3. 打开文件

   ofs.open("文件路径",打开方式);

4. 写数据

   ofs << "写入的数据";

5. 关闭文件

   ofs.close();

#include<iostream>
using namespace std;
#include<fstream>int main()
{ofstream ofs;ofs.open("test.txt", ios::out);ofs << "姓名:张三" << endl;ofs << "性别:男" << endl;ofs << "年龄:18" << endl;ofs.close();system("pause");return 0;
}

读文件


1. 包含头文件   

     #include <fstream>

2. 创建流对象  

   ifstream ifs;

3. 打开文件并判断文件是否打开成功

   ifs.open("文件路径",打开方式);

4. 读数据

   四种方式读取

5. 关闭文件

   ifs.close();

#include<iostream>
using namespace std;
#include <fstream>
#include <string>void tet()
{ifstream ifs;ifs.open("test.txt", ios::in);if (!ifs.is_open()){cout << "文件打开失败" << endl;return;}//第一种char buf[1024] = { 0 };while (ifs >> buf){cout << buf << endl;}//第二种char buf[1024] = { 0 };while (ifs.getline(buf,sizeof(buf))){cout << buf << endl;}//第三种string buf;while (getline(ifs, buf)){cout << buf << endl;}//第四种char c;while ((c = ifs.get()) != EOF){cout << c;}ifs.close();}int main() {tet();system("pause");return 0;
}

二进制文件


打开方式要指定为 ios::binary

二进制 写文件 


二进制方式写文件主要利用流对象调用成员函数write

函数原型 :ostream& write(const char * buffer,int len);

字符指针buffer:指向内存中一段存储空间。

len:读写的字节数

#include <fstream>
#include <string>class Person
{
public:char m_Name[64];int m_Age;
};//二进制文件  写文件
void test01()
{//1、包含头文件//2、创建输出流对象ofstream ofs("person.txt", ios::out | ios::binary);//3、打开文件//ofs.open("person.txt", ios::out | ios::binary);Person p = {"张三"  , 18};//4、写文件ofs.write((const char *)&p, sizeof(p));//5、关闭文件ofs.close();
}int main() {test01();system("pause");return 0;
}

二进制 读文件


二进制方式读文件主要利用流对象调用成员函数read

函数原型:istream& read(char *buffer,int len);

 

#include <fstream>
#include <string>class Person
{
public:char m_Name[64];int m_Age;
};void test01()
{ifstream ifs("person.txt", ios::in | ios::binary);if (!ifs.is_open()){cout << "文件打开失败" << endl;}Person p;ifs.read((char *)&p, sizeof(p));cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}int main() {test01();system("pause");return 0;
}
关键字:山西专业制作网站_合肥效果图制作公司_app推广方案_河南网站seo费用

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: