ofstream,ifstream,fstream读写文件

本文详细介绍了C++中用于文件操作的ofstream、ifstream和fstream类。通过实例展示了如何使用它们进行文件的读写操作,包括初始化、打开、关闭文件以及读写数据的方法。特别强调了ofstream在初始化时指定文件名的重要性,以及fstream的读写兼用特性。
摘要由CSDN通过智能技术生成

系列文章目录

前言

在编程总经常会用到读写文件,基本都是使用ofstream,ifstream,fstream

一、ofstream

写文件
cplusplus.com
在这里插入图片描述

#include <fstream>
ofstream         //文件写操作 内存写入存储设备 
ifstream         //文件读操作,存储设备读区到内存中
fstream          //读写操作,对打开的文件可进行读写操作 

在这里插入图片描述

在ofstream类中,成员函数open()实现打开文件的操作,从而将数据流和文件进行关联。下面这段代码依次打开0~9.txt 10个文件

#include<Windows.h>
#include<iostream>
#include<fstream>

#include<map>
#include<omp.h>
#include<string>
#include<vector>
#include<algorithm>
#include<sstream>
#include<gdiplus.h>

using namespace std;

int main(int argc, char** argv)
{

	for (int i=0; i<10; i++)
	{
		ofstream outFile;
		std::string fileName = to_string(i) + ".txt";
	
		outFile.open(fileName, std::ios::out);
		double temp = 0.0;

		outFile << std::to_string(temp) << "   "
			    << std::to_string(temp) << "   "
			    << std::to_string(temp) << "\n";

		outFile.close();
	}

	return 0;
}

在这里插入图片描述
每个文件输出内容
在这里插入图片描述
注意:如果代码写成下面这样:
也就是说:ofstream初始化的时候,不要指定文件,在调用open函数的时候再指定文件名,否则文件中的内容是空的,切记切记。我当时用了一个上午才发现问题,血淋淋的教训啊!!!!
还有就是写完文件记得关闭文件呦
在这里插入图片描述

二、ifstream

ifstream:读文件,用法跟ofstream差不多

ifstream fin;
	double data;
	fin.open(getFilePath() + "\\model\\20210408xiugai.txt");
	int k = 0;
	while (1)
	{
		if (fin.eof())
		{
			break;
		}
		else
		{
			fin >> data;
			fin >> data;
			weather1.vec_AirT.push_back(data);
			fin >> data;
			weather1.vec_Rh.push_back(data);
			fin >> data;
			weather1.vec_WindvSpeed.push_back(data);
			fin >> data;
			weather1.vec_Solar.push_back(data);
			//cout << k << endl;
			k += 1;
		}
	}
	fin.close();

三、fstream

fstream:可读可写数据,fstream 类为所有内建数据类型以及 std::string 和 std::complex 类型重载 << 和 >> 操作符。下面的例子示范了这些操作符的使用方法:

#include<Windows.h>
#include<iostream>
#include<fstream>

#include<map>
#include<omp.h>
#include<string>
#include<vector>
#include<algorithm>
#include<sstream>
#include<gdiplus.h>

using namespace std;

int main(int argc, char** argv)
{
	//fstream写数据
	for (int i=0; i<10; i++)
	{
		std::string fileName = to_string(i) + ".txt";
		fstream inOutFile;
		inOutFile.open(fileName, std::ios::out | std::ios::in | std::ios::trunc);
		double temp = i + 10;
		inOutFile << std::to_string(temp) << "   "
			    << std::to_string(temp) << "   "
			    << std::to_string(temp) << "\n";

		inOutFile.close();
	}
    //fstream读数据
	for (int i=0; i<10; i++)
	{
		std::string fileName = to_string(i) + ".txt";
		fstream inOutFile;
		inOutFile.open(fileName, std::ios::out | std::ios::in);
		double temp = 0;
		inOutFile >> temp;
				
		inOutFile.close();
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值