C++文件流(文本文件、二进制文件)demo

文本文件

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


void test02()
{
    
    
	ofstream ofs;
	ofs.open("test.txt", ios::out);
	ofs << "姓名:张三" << endl;
	ofs << "年龄:18" << endl;

	ofs.close();

}
void test03()
{
    
    
	ofstream ofs;
	ofs.open("test.txt", ios::trunc);
	ofs << "年龄:18" << endl;
	ofs.close();
}

void test04()
{
    
    
	ifstream ifs;
	ifs.open("test.txt", ios::in);

	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败";
		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,按行读入
	//string buf;
	//while (getline(ifs, buf))
	//{
    
    
	//	cout << buf << endl;
	//}
	
	//第四种
	//和第一种类似,逐字符读入,速度较慢
	//char c;
	//while ((c = ifs.get()) != EOF)
	//{
    
    
	//	cout << c;
	//}

	ifs.close();
}

int main() {
    
    

	
	test02();
	test03();
	test04();
	system("pause");

	return 0;
}

二进制写文件
函数原型 :ostream& write(const char * buffer,int len);
不是这个类型的话就得强制转换

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

示例:

#include <fstream>
#include <string>

class Person
{
    
    
public:	
	//尽量不要用C++的string
	//优先选用C的char
	char m_Name[64];
	int m_Age;
};

//二进制文件  写文件
void test01()
{
    
    
	//1、包含头文件

	//2、创建输出流对象
	ofstream ofs("person.txt", ios::out | ios::binary);
	
	//3、打开文件
	//ofs.open("person.txt", ios::out | ios::binary);

	Person p = {
    
    "张三"  , 18};

	//4、写文件
	ofs.write((const char *)&p, sizeof(p));

	//5、关闭文件
	ofs.close();
}

int main() {
    
    

	test01();

	system("pause");

	return 0;
}

二进制方式读文件主要利用流对象调用成员函数read

函数原型:istream& read(char *buffer,int len);
不是这个类型的话就得强制转换

参数解释:字符指针buffer指向内存中一段存储空间。len是读写的字节数

示例:

#include <fstream>
#include <string>

class Person
{
public:
	char m_Name[64];
	int m_Age;
};

void test01()
{
	ifstream ifs("person.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
	}

	Person p;
	ifs.read((char *)&p, sizeof(p));

	cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}

int main() {

	test01();

	system("pause");

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_48622537/article/details/110497713