ofstream,ifstream,fstream读写文件

系列文章目录

前言

在编程总经常会用到读写文件,基本都是使用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;
}

猜你喜欢

转载自blog.csdn.net/aoxuestudy/article/details/126099954