栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++:文件操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++:文件操作

文件操作
  • 文本文件:写文件
  • 文本文件:读文件
  • 二进制文件:写文件
  • 二进制文件:读文件

程序运行的过程中产生的数据都属于临时数据 程序一旦结束运行的话这些数据也会被释放,所以就要通过文件来讲数据持久化
C++中对文件操需要包含头文件

文件一般分为两种类型:文本文件和二进制文件

  • 文本文件:文件以文本的ASCLL码的形式存储在计算机内i
  • 二进制文件:文件以文本的二进制形式存储在计算机内 用户一般不能直接读懂他们

操作文件的三大类:

  • 写操作:ofstream
  • 读操作:ifstream
  • 读写操作:fstream
文本文件:写文件

写文件得操作流程:

  • 包含头文件
  • 创建流对象 ofstream ofs
  • 打开文件 ofs.open(“文件路径”,打开方式)
  • 写数据ofs<<
  • 关闭文件 ofs.close()

文件的打开方式主要有一下几种:

#include 
#include 
#include //c++中字符串需要添加这个头文件
#include 
using namespace std;


int main()
{
	ofstream ofs;
	ofs.open("E:\Users\Desktop\C++test.txt", ios::out);
	ofs << "C++ test 1" << endl;
	ofs << "C++ test 2" << endl;
	ofs.close();
	system("pause");
	return 0;
}

文本文件:读文件

读文件得操作流程:

  • 包含头文件
  • 创建流对象 ofstream ifs
  • 打开文件并判断打开文件是否成功 ofs.open(“文件路径”,打开方式)
  • 读数据 四种读取方式
  • 关闭文件 ofs.close()

第一种方式

#include 
#include 
#include //c++中字符串需要添加这个头文件
#include 
using namespace std;


int main()
{
	ifstream ifs;
	ifs.open("E:\Users\Desktop\C++test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "打开文件失败!" << endl;
		return 0;
	}
	
	cout << "The first read way" << endl;//The first read way
	char str1[1024] = {0};
	while (ifs >> str1)
	{
		cout << str1 << endl;
	}
	ifs.close();

	system("pause");
	return 0;
}


第二种方式

#include 
#include 
#include //c++中字符串需要添加这个头文件
#include 
using namespace std;


int main()
{
	ifstream ifs;
	ifs.open("E:\Users\Desktop\C++test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "打开文件失败!" << endl;
		return 0;
	}
	
	cout << "The second read way" << endl;//The second read way
	char str[1024] = {0};
	while (ifs.getline(str,sizeof(str)))
	{
		cout << str << endl;
	}
	ifs.close();

	system("pause");
	return 0;
}


第三种方式

#include 
#include 
#include //c++中字符串需要添加这个头文件
#include 
using namespace std;


int main()
{
	ifstream ifs;
	ifs.open("E:\Users\Desktop\C++test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "打开文件失败!" << endl;
		return 0;
	}
	
	cout << "The third read way" << endl;//The third read way
	string str;
	while (getline(ifs,str))
	{
		cout << str << endl;
	}
	ifs.close();

	system("pause");
	return 0;
}


第四种方式

#include 
#include 
#include //c++中字符串需要添加这个头文件
#include 
using namespace std;


int main()
{
	ifstream ifs;
	ifs.open("E:\Users\Desktop\C++test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "打开文件失败!" << endl;
		return 0;
	}
	
	cout << "The fourth read way" << endl;//The fourth read way
	char str;
	while ( (str =ifs.get())!=EOF)
	{
		cout << str << endl;
	}
	ifs.close();

	system("pause");
	return 0;
}


通过四种读文件的方式可以分析对比,第2,3种的方式都是按行读取的 是我们一般中比较常用的的方式

二进制文件:写文件

后期增加

二进制文件:读文件

后期增加

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/928661.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号