C++学习 --文件

文件操作步骤:

1, 包含头文件#include<fstream>

2, 创建流对象:ofstream ofs

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

4, 写数据:ofs << "写入数据"

5, 关闭文件:ofs.close()

打开方式:ios::in 读文件打开, ios:out,写文件打开, ios::ate, 打开文件, 定位到尾部

ios::trunc, 如果文件存在先删除, 在创建, ios::binary, 二进制文件

1, 写文件

cpp 复制代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <set>
#include <fstream>

using namespace std;

void test()
{	
	ofstream aaa;
	aaa.open("test.txt", ios::out);
	aaa << "张三, 28";
	aaa.close();
}

int main()
{	
	test();

	system("pause");

	return 0;
}

2, 读文件

cpp 复制代码
ifstream aaa;
aaa.open("test.txt", ios::in);

//第一种方式
/*char buf [1024] = { 0 };
while (aaa >> buf)
{
	cout << buf;
}*/

//第二种方式
/*char buf[1024] = { 0 };
while (aaa.getline(buf, sizeof(buf)))
{
	cout << buf;
}*/

//第三种方式
/*string buf;
while (getline(aaa, buf))
{
	cout << buf;
}*/

//第四种方式
char c;
while ((c = aaa.get()) != EOF)
{
	cout << c;
}

3, 二进制文件

3-1, 写文件

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

void test()
{	
	Person p = { "张三", 18 };
	ofstream aaa("test1.txt", ios::out | ios::binary);
	//aaa.open("test1.txt", ios::out | ios::binary);
	aaa.write((const char*)&p, sizeof(Person));
	aaa.close();
}

3-2, 读文件

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

void test()
{	
	Person p;
	ifstream aaa("test1.txt", ios::out | ios::binary);
	//aaa.open("test1.txt", ios::out | ios::binary);
	aaa.read((char*)&p, sizeof(Person));
	cout << p.m_name << endl;
	cout << p.m_age << endl;
	aaa.close();
}
相关推荐
赵谨言4 分钟前
摘要本研究旨在构建一套基于OpenCV与CNN融合技术的银行卡号自动识别系统,重点解决不同银行卡号字体格式差异、倾斜污损等复杂场景下的识别难题
大数据·开发语言·经验分享·python
147API8 分钟前
Claude JSON 稳定输出:Schema 校验与修复回路(Kotlin)
开发语言·kotlin·json·claude
于先生吖9 分钟前
Java 打车小程序 APP 源码 顺风车滴滴跑腿系统完整实现
java·开发语言·打车系统
@我漫长的孤独流浪18 分钟前
C算法设计与分析------程序设计代码
数据结构·c++·算法
怪侠_岭南一只猿19 分钟前
爬虫阶段一实战练习题:爬取豆瓣电影 Top250 复盘
css·经验分享·爬虫·python·学习·正则表达式
zh路西法23 分钟前
【C语言简明教程】(一):数据类型,表达式与控制结构
c语言·开发语言
他们都不看好你,偏偏你最不争气23 分钟前
【iOS】block
开发语言·ios·objective-c·block·闭包
工业甲酰苯胺24 分钟前
PHP闭包中static关键字的核心作用与底层原理解析
android·开发语言·php
liu****25 分钟前
1.反向迭代器实现思路
数据结构·c++·反向迭代器·vector·list
冬夜戏雪28 分钟前
【学习日记】
java·开发语言·数据库