C++读写文件操作

1.文件操作需要包含头文件fstream

2.文件操作分两种

  1. 文本文件:ASCII码
  2. 二进制文件:一般人读不懂

3.操作三大类

  1. ofstream:写操作
  2. ifstream:读操作
  3. fstream:读写写操作

4. 打开方式:

在这里插入图片描述

举例

1. 写文件举例

  1. 包含头文件fstream
  2. 创建流对象
  3. 打开文件
  4. 写数据
  5. 关闭文件
#include<iostream>
using namespace std;
#include<string>

//1.头文件
#include<fstream>


int main()
{
    
    
	//2.创建流
	ofstream f;
	//3.打开文件
	f.open("D://1.txt", ios::out);//没有的话会自动创建
	//4.写入
	f << "这是文件";
	//5.关闭
	f.close();	
}

2. 读文件举例

  1. 包含头文件fstream
  2. 创建流对象
  3. 打开文件
  4. 读数据
  5. 关闭文件
    如果乱码:中文文档用 将文件另存为,编码方式选择ANSI,并覆盖原来的文件
#include<iostream>
using namespace std;
#include<string>

//1.头文件
#include<fstream>


int main()
{
    
    
	//2.创建流
	ifstream f;
	
	//3.打开文件
	f.open("D://1.txt", ios::in);//没有的话会自动创建
	
	//4.读取
	
//	//方式1,流,变量读入
//	cout << "\n方式1" << endl;
//	char c[1024];
//	while( f >> c )
//	{
    
    
//		cout << c << endl;
//	}
	
//	//方式2,行读入
//	cout << "\n方式2" << endl;
//	char c[1024];
//	while( f.getline(c, sizeof(c)) )
//	{
    
    
//		cout << c << endl;
//	}
	
//	//方式3,流+string对象
//	cout << "\n方式3" << endl;
//	string c;
//	while( getline(f, c) )
//	{
    
    
//		cout << c << endl;
//	}	
	
	//方式4,字符读入,EOF文件末尾
	cout << "\n方式4" << endl;
	char c;
	while( (c = f.get()) != EOF )
	{
    
    
		cout << c;
	}
	
	//5.关闭
	f.close();	
}

3. 二进制写

  • 写binary
  • 数据对象,write写入
    在这里插入图片描述
#include<iostream>
using namespace std;
#include<string>

//1.头文件
#include<fstream>

class Person
{
    
    
	public:
		//二进制方式最好用char
		char name[1024];
		int age;
};


int main()
{
    
    
	//2.创建流
	ofstream f;
	
	//3.打开文件,二进制方式,写ios::binary
	f.open("D://1.txt", ios::out | ios::binary);//没有的话会自动创建
	
	//4.写入 
	Person p{
    
    "张三",19};//结构体的那种赋值方式
	f.write( (const char *)&p, sizeof(Person) );

	//5.关闭
	f.close();	
}

4. 二进制读

在这里插入图片描述

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

//1.头文件
#include<fstream>

class Person
{
    
    
	public:
		//二进制方式最好用char
		char name[1024];
		int age;
};


int main()
{
    
    
	//2.创建流
	ifstream f;
	
	//3.打开文件,二进制方式,写ios::binary
	f.open("D://1.txt", ios::in | ios::binary);//没有的话会自动创建
	
	//4.写入 
	Person p;
	f.read( (char *)&p, sizeof(Person) );
	
	cout << p.age << ' ' << p.name <<endl;
	
	//5.关闭
	f.close();	
}

猜你喜欢

转载自blog.csdn.net/foolbirdM/article/details/125610426