ofstream,ifstream,fstream读写文件

网友投稿 804 2022-10-06

ofstream,ifstream,fstream读写文件

ofstream,ifstream,fstream读写文件

系列文章目录

文章目录

​​系列文章目录​​​​前言​​​​一、ofstream​​​​二、ifstream​​​​三、fstream​​

前言

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

一、ofstream

写文件

​​cplusplus.com​​

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

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

#include#include#include#include#include#include#include#include#include#includeusing 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#include#include#include#include#include#include#include#include#includeusing 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;}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序中Video API的解析(微信小程序中的阿玛尼是官方吗)
下一篇:Istio的扩展和定制
相关文章

 发表评论

暂时没有评论,来抢沙发吧~