目录

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;
}
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
加瓦点灯19 分钟前
观察者模式:解耦对象间的依赖关系
开发语言·javascript·观察者模式
愚润求学21 分钟前
Linux开发工具——apt
linux·服务器·开发语言
程序员小赵同学22 分钟前
AI Agent设计模式二:Parallelization
开发语言·python·设计模式
时光话29 分钟前
Lua:第1-4部分 语言基础
开发语言·lua
欧宸雅34 分钟前
Clojure语言的持续集成
开发语言·后端·golang
the_nov1 小时前
25.Reactor
linux·c++
胡斌附体1 小时前
qt tcpsocket编程遇到的并发问题
开发语言·网络·qt·并发编程·tcpsocket
学c真好玩1 小时前
4.3python操作ppt
开发语言·python·powerpoint
数小模.1 小时前
MATLAB中plot函数的详细参数表
开发语言·matlab
神里流~霜灭2 小时前
数据结构:二叉树(三)·(重点)
c语言·数据结构·c++·算法·二叉树·红黑树·完全二叉树