C++文件处理

1、简介:

数据存储的两种方式:文件和数据库

IOS_base是基类派生出IOS类

IOS派生出-istream类和ostream类

        istream定义cin    

        ostream定义cout、cerr、clog

istream类派生出,ifstream读文件

ostream类派生出,ofstream写文件

istream和ostream派生出iostream类

iostream派生出fstream类,读写文件

 2、写入文件

文本文件一般以行的形式组织数据

头文件:#include <fstream>

类:ofstream(output file stream)

C语言我一般习惯用fprintf,把数据写入文件

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>//oftream类需要包含的头文件
using namespace std;

int main()
{
	string file = "E:\\C\\visualStudio\\project_management\\C++_sys_test\\test.txt";
	//ofstream fout;//file output文本输出对象
	//fout.open(file);
	ofstream fout(file,ios::out);//类似于c的w
	//ofstream fout(file, ios::app);//类似于c的a

	if (!fout.is_open()) {
		cout << "open fail:" <<file << endl;
		return 1;
	}

	fout << "nike 18 90" << endl;
	fout << "adidas 20 99" << endl;
	fout << "senma 28 93" << endl;

	fout.close();//关闭文件,fout对象失效前会自动调用close();
	return 0;
}
nike 18 90
adidas 20 99
senma 28 93

3、读取文件

包含头文件:#include <fstream>

类:ifstream

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>//oftream类需要包含的头文件
#include <string>
using namespace std;

int main()
{
	string file = "E:\\C\\visualStudio\\project_management\\C++_sys_test\\test.txt";
	//ofstream fout;//file output文本输出对象
	//fout.open(file);
	ifstream fin(file,ios::in);//读取

	if (!fin.is_open()) {
		cout << "open fail:" <<file << endl;
		return 1;
	}

	//第一种方法
	//string buffer;
	//while (getline(fin, buffer)) {
	//	cout << buffer << endl;
	//}
	
	//第二种方法
	//char buffer[101];
	一定要保证缓冲区足够大
	//while (fin.getline(buffer, 100)) {
	//	cout << buffer << endl;
	//}

	//第三种方法
	string buffer;
	while (fin >> buffer) {
		cout << buffer << endl;
	}


	fin.close();//关闭文件,fout对象失效前会自动调用close();
	return 0;
}

4、以二进制方式打开文件

ios::binary

fout.open(file,ios::app | ios::binary);

fout.write((const char*)&girl,sizeof(st_girl));

5、读取二进制文件

二进制文件格式多种多样

程序员定义的二进制格式,只有自己知道

通用的二进制文件格式:mp3、mp4、bmp、jpg、png

fin.read((char *)&girl,sizeof(girl)))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值