C++ 文件操作

文本文件的操作:文件以文本的ASCLL码的形式存储在计算机

包含头文件流<fstream>

写:ofstream

读:ifsream

可读可写:fstream

写文件操作步骤

包含头文件--->创建流对象----->打开文件---->写入数据----->关闭文件

文件打开的方式:

写文件示例!

cpp 复制代码
#include<iostream>
#include<fstream>
using namespace std;

void test()
{
//创建对象流
	ofstream ofs;
	//指定打开方式
	ofs.open("test.txt", ios::out);
	//写入内容
	ofs << "123123一二三123!" << endl;
	ofs << "123123一二三123!" << endl;
	ofs << "123123一二三123!" << endl;
	ofs << "123123一二三123!" << endl;
	//关闭文件
	ofs.close();
}

int main()
{

	test();
	
	system("pause");
	return 0;
}

读文件操作:5步

cpp 复制代码
void test()
{
//创建对象流
	ifstream ifs;
	//指定打开方式
	ifs.open("test.txt", ios::in);
	//打开文件,判断是否打开成功
	if (!ifs.is_open())
	{
		cout << "open erro" << endl;
		return;
	}
	//读数据
	char buffer[1024];
	while (ifs >> buffer)
	{
		cout << buffer << endl;
	}

	/*
	成员函数getline 获取一行
	char buf[1024]={0};
	将读到的数据放入buf
	while(ifs.getline(buf,sizeof(buf))
	{
	cout<<buf<<endl;
	}
	*/


	/*
	string buf;
	while(getline(ifs,buf))
	*/
	//关闭文件
	ifs.close();
}

int main()
{

	test();
	
	system("pause");
	return 0;
}

二进制文件的读写!

打开方式需要指定: iso::binary

利用流对象调用成员函数write

ostream& write(const chatr*buffer,int len);

字符指针 buffer指向内存中的一段储存空间,len为读取的字节数

cpp 复制代码
class Person
{
public:
	char name[64];
	int m_age;
};

void test()
{
//创建对象流
	ofstream ofs;
	ofs.open("person,txt",ios::out|ios::binary);
	//ofstream ofs("person,txt",ios::out|ios::binary);
	//写文件
	Person p = { "yyyyy",20 };
	ofs.write((const char*)&p, sizeof(Person));
}

读取二进制文件

read函数

cpp 复制代码
void test02()
{
	ifstream ifs;
	ifs.open("person,txt", ios::out | ios::binary);
		if (!ifs.is_open())
		{
			cout << "open erro" << endl;
			return;
		}
		Person p;
		ifs.read((char*)&p, sizeof(Person));
		cout << p.m_age << endl;
		cout << p.name << endl;
}
相关推荐
Jayden_Ruan20 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊20 小时前
启动文件Startup_vle.c
c语言·开发语言
liulun20 小时前
Skia如何渲染 Lottie 动画
c++·动画
VBA633720 小时前
VBA之Word应用第四章第二节:段落集合Paragraphs对象(二)
开发语言
点云SLAM21 小时前
C++ 常见面试题汇总
java·开发语言·c++·算法·面试·内存管理
xiaowu0801 天前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
edjxj1 天前
Qt图片资源导入
开发语言·qt
qq_25929724731 天前
QT-事件
开发语言·qt
专注VB编程开发20年1 天前
CSS 的命名方式像是 PowerShell 的动词-名词结构,缺乏面向对象的层级关系
开发语言·后端·rust
古译汉书1 天前
嵌入式铁头山羊stm32-ADC实现定时器触发的注入序列的单通道转换-Day26
开发语言·数据结构·stm32·单片机·嵌入式硬件·算法