首先是C++的版本,完成对txt文件的读写操作
* 读文件三大类 : (1)ofstream : 写文件 (2)ifstream : 读文件 (3)fsream : 读写文件
1 文本文件
- 1 写文件
步骤:
(1)包含头文件 #include < fstream > (2)创建流对象 ofstream ofs
(3)打开文件 ofs.open (“文件路径” ,打开方式) (4)写数据 ofs <<“写入数据”
(5)关闭文件 ofs.close()
文件的写操作,可以说是比较无脑了,判断是否打开成功,然后一股脑的把数据扔进去就可以了
std::ofstream save_parameter;
save_parameter.open("parameter.txt", std::ios::out);
if(!save_parameter.is_open()){
std::cout<<"open the parameter.txt failed..."<<std::endl;
}
else{
save_parameter<<_polyCoeff;
save_parameter.close();
}
std::ofstream save_timer;
save_timer.open("save_timer.txt", std::ios::out);
if(!save_timer.is_open()){
std::cout<<"open the save_timer.txt failed..."<<std::endl;
}
else{
save_timer<<_polyTime;
save_timer.close();
}
文件的读操作
- 2 读文件与写文件步骤类似,但读取方式比较多。
步骤:
(1)包含头文件 #include < fstream > (2)创建流对象 ifstream ifs
(3)打开文件并判断文件是否打开成功 ifs.open (“文件路径” ,打开方式) (4)读数据 四种方式读取
(5)关闭文件 ifs.close()
首先定义两个Eigen数组
Eigen::Matrix<double,MINISNAP_ROW,MINISNAP_COL>parameter;
Eigen::Matrix<float,MINISNAP_ROW,1>poly_timer;
通过如下通用代码完成对应文件的读操作以及赋值操作
std::fstream infile;
infile.open("/home/chasing/Downloads/mavros_controller/parameter.txt",std::ios::in);
if(!infile.is_open()){
ROS_ERROR("error for load the parameters.txt....");
exit(EXIT_FAILURE);
}else{
for(uint8_t i=0;i<MINISNAP_ROW;i++){
for(uint8_t j=0;j<MINISNAP_COL;j++){
infile >> parameter(i,j);
}
}
}
infile.close();
for(uint8_t i=0;i<MINISNAP_ROW;i++){
for(uint8_t j=0;j<MINISNAP_COL;j++){
std::cout<< parameter(i,j)<<"\t";
}
std::cout<<std::endl;
}
std::fstream timefiles;
timefiles.open("/home/chasing/Downloads/mavros_controller/save_timer.txt",std::ios::in);
if(!timefiles.is_open()){
ROS_ERROR("error for load the timer.txt...");
exit(EXIT_FAILURE);
}else{
for(uint8_t i=0;i<MINISNAP_ROW;i++){
timefiles >> poly_timer(i);
}
ROS_INFO("reading the timer data successfully...");
}
timefiles.close();
然后是python的版本,完成对txt文件的读写操作
data = open("logfile.txt","r")
print(data.read())
print(data.readline())
print(data.readlines())
其中 r 表示以读的方式打开文件,对应的是"a+"表示是以追加写的形式打开。
read()函数表示一次性全部读取过来,返回的数据类型是字符串。
readline()表示只读取一行数据。 readlines()表示读取多行数据,返回的是一个元祖
然后是对应的数据的写操作。测试代码如下:
a = 20
b = np.random.random((2,3))
data = open("logfile.txt","a+")
print("This is a test, a= %.3f" %a, file=data)
print(b,file=data)
data.close()
Remark: 文件的读和写要分开打开完成操作。