C++读写文件(十六)

32 篇文章 0 订阅
  1. 头文件  #inlcude < fstream>

  2. 写文件 
    1.  ofstream  ofs (文件路径,打开方式  ios::out )
    2. 判断文件是否打开成功  ofs.is_open
    3. ofs << “…”
    4. 关闭文件  ofs.close();
  3. 读文件
    1. ifstream  ifs(文件路径,打开方式  ios::in)
    2. 判断文件是否打开成功  ofs.is_open
    3. 利用4种方式 对文件进行读取
    4. 关闭文件  ifs.close();

文件读写、 

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

void write_data() {
	//ofstream ofs("./text.txt",ios::out | ios::trunc);
	ofstream ofs;
	ofs.open("./text.txt", ios::out | ios::trunc);

	if (!ofs.is_open()) {
		cout << "文件打开失败" << endl;
		return;
	}

	ofs << "abcdefg" << endl;
	ofs << "abcdefg" << endl;
	ofs << "abcdefg" << endl;
	ofs << "abcdefg" << endl;
	ofs.close();
}

void read_data() {
	//ifstream  ifs;
	//ifs.open("./text.txt", ios::in);
	ifstream  ifs("./text.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() {
	write_data();
	read_data();
	system("pause");
	return EXIT_SUCCESS;
}

二进制文件读写实例、 

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<fstream>
#include<string>

using namespace std;
class Maker
{
public:
	string name;
	int age;
public:
	Maker() {}
	Maker(string name, int age)
	{
		this->name = name;
		this->age = age;
	}
};

//写文件
void test01()
{
	Maker *m1=new Maker("悟空", 18);
	Maker *m2 = new Maker("贝吉塔", 22);

	ofstream ofs;
	ofs.open("test.txt", ios::out | ios::trunc | ios::binary);
	if (!ofs.is_open())
	{
		cout << "打开失败" << endl;
	}
	//写
	ofs.write((const char*)&m1, sizeof(Maker));
	ofs.write((const char*)&m2, sizeof(Maker));

	ofs.close();
}
//读文件
void test02()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "打开失败" << endl;
	}

	//读
	Maker *m1;
	Maker *m2;

	ifs.read((char*)&m1, sizeof(Maker));
	ifs.read((char*)&m2, sizeof(Maker));

	cout << "Name:" << m1->name << " Age:" << m1->age << endl;
	cout << "Name:" << m2->name << " Age:" << m2->age << endl;

	delete m1;
	delete m2;
	ifs.close();
}

int main()
{
	test01();
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值