ifstream/ofstream实现读取txt文件信息和保存信息到txt文件
一、原理
1、 我们知道c++中可以使用cout<<a;把a向屏幕中输入,cin>>b从键盘输入到b;通过添加iostream头文件就可以实现。其实可以理解为:cout是一个写入文件的接口,屏幕是保存信息的txt文件;cin是一个读取文件的接口,键盘是其要读取信息的txt文件。
2、所以这里的ofstream就是创建一个类似cout的接口,来连接数据和文件夹保存数据;ifstream就是创建一个类似cin的接口,来连接文件和代码中数据,输入数据。
二、ofstream
1、创建写接口方式
方法一:
//txt文件路径
string input_text_path = "C:\\Users\\tudejiang\\Desktop\\text.txt";
ofstream text_input(input_text_path);
方法二:
//txt文件路径
string input_text_path = "C:\\Users\\tudejiang\\Desktop\\text.txt";
ofstream text_input;
text_input.open(input_text_path);
2、写操作
方法一:<<(类似cout<<)
text_input <<i << endl;
三、ifstream
1、创建读接口操作(和ofstream一样)
方法一
//txt文件路径
string output_text_path = "C:\\Users\\tudejiang\\Desktop\\img_set.txt";
//创建文件接口
ifstream text_output(output_text_path);
方法二
//txt文件路径
string output_text_path = "C:\\Users\\tudejiang\\Desktop\\img_set.txt";
//创建文件接口
ifstream text_output;
text_output.open(output_text_path);
2、写操作
方法一:getline()函数读取一行
while (getline(text_output,text))
{
cout << text << endl;
}
方法二:>>(类似cin>>a)
text_output >> text;
简单完整测试代码
#include<iostream>
#include<fstream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
//单行文件信息
string text;
//txt文件路径
string output_text_path = "C:\\Users\\tudejiang\\Desktop\\img_set.txt";
//创建文件接口
ifstream text_output;
text_output.open(output_text_path);
while (getline(text_output,text))
{
cout << text << endl;
}
//保存信息到文档
//txt文件路径
string input_text_path = "C:\\Users\\tudejiang\\Desktop\\text.txt";
ofstream text_input;
text_input.open(input_text_path);
for (int i = 0; i < 10; i++)
{
text_input <<i << endl;
}
return 0;
}
说明:
由于读取和存储存在各种复杂的格式,大家在理解ifstream和ofstream的工作原理后可以对应的根据具体情况来完成格式规范。