前言
最近在学习有关于卡尔曼滤波方面的知识,其中会涉及到一部分的测量数据和预测数据。这里记录一下C++关于数据的读写操作
写数据到文件中
关于文件流的操作在网站菜鸟教程中有一些简介,这里我就不再重复记录一些基础操作了,下面就以一个实例加深我们对文件流操作的印象。
#include<iostream>
#include<time.h>
#include<string>
#include<fstream>
using namespace std;
int main(int agrc,char* argv[])
{
time_t currentTime = time(NULL);//
char chCurrentTime[256];
strftime(chCurrentTime,sizeof(chCurrentTime),"%Y%m%d %H%M%S",localtime(¤tTime));
string stCurrentTime = chCurrentTime;
string filename ="/home/wf/data-"+ stCurrentTime +".txt";
ofstream fout;
fout.open(filename.c_str());//创建并打开一个文件
char a,b,c,d;
int i = 0;
while (i<2)
{
cin>>a>>b>>c>>d;
fout<<a<<" "<<b<<" "<<c<<" "<<d<<" " << endl; //开始创建流
i++;
}
fout<<flush; //将流写入硬盘
fout.close(); //关闭文件
}
我们文件命名的名称为程序运行时候的时间戳,具体命名参照自己的喜好。其实文件命名以时间来命名是一个好习惯,我在某实习项目上吃过这种亏,自己不知道代码是啥时候写的了。(实习的时候从一位工程师那里学到的 )。
往文件中写 用到的是ofstream对象,在往文件中写数据之前首先要打开文件,用标准函数open(),我们如果输入文件名字默认是在当前文件夹下创建文件,我们也可以指定存放的路径,在文件命名前面加上相对应的绝对路径即可。
void open(const char *filename, ios::openmode mode);
写入文件我们用流插入运算符(<<)向文件中写入信息,这里对象采用的是ofstream,再写完文件的时候要记得关闭。
读取文件中的数据
读取文件中的数据和往文件中写如数据差不多,我们需要修改的是读取文件中的对象采用的对象是ifstream,首先要打开文件,然后读取文件中的内容,读取文件这里主要阐述两种读取方式。读取完毕之后要将文件关闭。
1. 用函数getline(对象,读取类型string)该函数可以将文件中的所有内容都读取出来,包括空格
2.用流提取运算符(>>)从文件读取信息,这里将忽略空格。
#include<iostream>
#include<time.h>
#include<string>
#include<fstream>
using namespace std;
int main(int agrc,char* argv[])
{
time_t currentTime = time(NULL);//
char chCurrentTime[256];
strftime(chCurrentTime,sizeof(chCurrentTime),"%m_%d-%H_%M_%S",localtime(¤tTime));
string stCurrentTime = chCurrentTime;
string filename ="/home/wf/data-"+ stCurrentTime +".txt";
cout <<"filename: " << filename <<endl;
ofstream fout;
fout.open(filename.c_str());//创建并打开一个文件
char a,b,c,d;
int i = 0;
while (i<1)
{
cin>>a>>b>>ct>>d;
fout<<a<<" "<<b<<" "<<c<<" "<<d<<" " << endl; //开始创建流
i++;
}
fout<<flush; //将流写入硬盘
fout.close(); //关闭文件
ifstream fin;
fin.open(filename);
// cout<< "Read from the file: " <<endl;
// char bufLine[4] ={0};
// for(int i=0; i <4;i++)
// {
// fin >>bufLine[i]; //kongge
// cout<< bufLine[i]<< endl;
// }
if(fin.is_open())
{
cout <<"文件打开成功!" <<endl;
string str ;
while (getline(fin,str))
{
cout << str << endl;
}
}
else
{
cout << "文件打开失败!"<< endl;
}
fin.close();
}