1 将数据写入文本文件
// 文本文件的写入
#include<iostream>
#include<fstream>
using namespace std;
//创建一个空文本,并且规定以追加方式(ios::app)添加数据
ofstream foutput("gps.txt",ios::app);
//写入需要添加的数据
foutput<<info.Longitude<<","<<info.Latitude<<","<<info.Speed<<","<<info.Easting<<","<<info.Northing<<","<<info.Heading<<"\n";
//关闭文本文档
foutput.close();
2 ofstream,ifstream,fstream的使用
#include <iostream>
// C++ I/O类软件包处理文件输入和输出的方式,要让程序写入文件或者读取文件内容,必须要包含头文件fstream
#include <fstream> // std::ifstream,不加std的话只是帮助编译器找到相关的声明
using namespace std;
int main(int argc, char *argv[])
{
// 1-1 ofstream,只写模式打开文件,如果文件不存在,可以创建文件
// // 创建文件方式1:
// // ofstream: 只写模式打开文件,二个参数为打开模式,可以不写,用默认的;,如果文件不存在,可以创建文件
// ofstream file("new_create.txt", fstream::out);
// if (file) cout << " new file created" << endl;
// // 创建文件方式2:open函数打开ia文件,不存在则另外创建一个
// // 判断文件是否创建或打开成功,open函数也可以打开文件
ofstream file3;//有默认构造函数
file3.open("new.txt");
if (file3.is_open()) cout << "file3 is open" << endl;
string s = "perfect is shit";
file3<<s<<endl;
// 1-2 ifstream 读取该文件,并把内容显示到屏幕
// 注意:读取文件时该文件要默认放在src文件夹下
// 光读取文件的方式1:
// ifstream in1("a.txt");
// if (in1.is_open()) cout << "已存在的文件打开成功" << endl;
// 光读取文件的方式2:
// ifstream in2;
// in2.open("b.txt");
// if (in2.is_open()) cout << "in2 打开成功" << endl;
// 光读取文件的方式3:
// 注意:ifstream在缺省情况下会以读的模式打开一个文件,并把文件指针定在文件的起始处。
std::ifstream ifs("a.txt");
if(ifs.is_open())
{
// <<”插入器,向流输出数据
std::cout<<"a.txt file is already open"<<endl;
}
// >>”析取器,向流输出数据;
double init_pos_x, init_pos_y;
ifs >> init_pos_x>>init_pos_y;
cout<<"init_pos_x:="<<init_pos_x<<"init_pos_y:="<<init_pos_y<<endl;
// string s2;
// getline(ifs,s2);
// cout<<"读入的数据为"<<s2<<endl;
ifs.good() ; //判断文件是否读取正常,正常的没有报错的情况下会返回false
cout<<ifs.good() <<endl; //0为false,1为true
// ifs.close();
// 1-3 读写模式
// fstream fs4("new.txt");//默认为读写模式,也可以显示指定
// if(fs4.is_open())
// {
// std::cout<<"hcf.txt file is already open"<<endl;
// }
// string s3 = "learning by doing\n";
// fs4 << s3<<endl;
return 0;
}
程序说明
fstream:默认为读写模式
ifstream:默认只读文件,仅在文件存在情况下才可以读取
ofstream:只写模式打开文件,如果文件不存在,可以创建文件
3 ifstream读取文件的三种方式
// 光读取文件的方式3:
// 注意:ifstream在缺省情况下会以读的模式打开一个文件,并把文件指针定在文件的起始处。
std::ifstream ifs("a.txt");
if(ifs.is_open())
{
// <<”插入器,向流输出数据
std::cout<<"a.txt file is already open"<<endl;
}
// 1-2-1 一行行读取txt文本数据
// string s2;
// while (getline(ifs,s2))
// {
// cout<<s2<<endl;
// }
// 1-2-2 一字符一字符读,忽略空格与回车
// char c;
// while (!ifs.eof())
// {
// ifs>> c;
// cout << c << endl;
// }
// 1-2-3 一字符一字符读,不忽略空格与回车
char c;
ifs >> noskipws;
while (!ifs.eof())
{
ifs>> c;
cout << c << endl;
}
// 1-2-4 分割多行文件中每行用空格隔开的字符串,每行包含的小数数字个数不同
string line;
while (getline(ifs,line)) //获取文件的一行字符串到line中
{
// stringstream包含了基本数据类型的转换,比printf(s,”%d”,n);// s中的内容为“10000”更方便
stringstream ss(line); //初始化法1,,将x输入流
double x;
while (ss>>x)// 抽取ss中的值到x
{
cout<<x<<"\t";
}
cout<<endl;
}