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;
}
相关推荐
样例过了就是过了4 分钟前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
Bat U14 分钟前
JavaEE|多线程初阶(七)
java·开发语言
谭欣辰24 分钟前
C++ 排列组合完整指南
开发语言·c++·算法
橙子也要努力变强1 小时前
信号捕捉底层机制-机理篇2
linux·服务器·c++
foundbug9991 小时前
自适应滤除直达波干扰的MATLAB实现
开发语言·算法·matlab
盐焗鹌鹑蛋1 小时前
【C++】stack和queue类
c++
XDH_CS1 小时前
MySQL 8.0 安装与 MySQL Workbench 使用全流程(超详细教程)
开发语言·数据库·mysql
小短腿的代码世界2 小时前
Qt实时盈亏计算深度解析:从持仓数据到动态盈亏展示
开发语言·qt
小康小小涵2 小时前
基于ESP32S3实现无人机RID模块底层源码编译
linux·开发语言·python