背景:
想用库去创建文件,没有文件就创建,存在则往文件末尾添加内容
//写文件
fstream fs;
fs.open("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt", ios::in);
if(!fs) std::cout << "file not exist " << std::endl;
ofstream outfile("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt", ios::app);
if (outfile.is_open()){
std::cout << "file exist " << std::endl;
outfile << std::to_string(lidarData_.line_dis) << std::endl;
outfile.close();
}
//读文件
fstream fs_read;
fs_read.open("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt", ios::in);
if(!fs_read) std::cout << "file not exist " << std::endl;
ifstream outfile_1("/home/catkin_zed/src/pcl_detection/zed2_pic/21-12-27 13:34:01/rgb/depth/new_create.txt");
if (outfile_1.is_open()){
std::cout << "file exist " << std::endl;
std::string outString;
while(outfile_1.peek() != EOF) //读完最后一个数据时,eofbit还是false,只有继续往下读才会发现到了文末才是true,所以用peek()
{
getline(outfile_1, outString);
std::cout << "outString:" << outString << std::endl;
}
outfile_1.close();
}
else{
std::cout << "open file faild" << std::endl;
}
fstream介绍
以下转载于:https://blog.csdn.net/qq_34801341/article/details/105745850
ofstream流:
以ios::app打开(或者“ios::app|ios::out”),如果没有文件,那么生成空文件;如果有文件,那么在文件尾追加。
以ios::app|ios::in打开,不管有没有文件,都是失败。
以ios::ate打开(或者”ios::ate|ios::out”),如果没有文件,那么生成空文件;如果有文件,那么清空该文件
以ios::ate|ios::in打开,如果没有文件,那么打开失败;如果有文件,那么定位到文件尾,并可以写文件,但是不能读文件
ifstream流:
以ios::app打开(“ios::app|ios::out”),不管有没有文件,打开都是失败。
以ios::ate打开(“ios::ate|ios::out”),如果没有文件,打开失败
如果有文件,打开成功,并定位到文件尾,但是不能写文件
fstream流,
默认是ios::in,所以如果没有文件,ios::app和ios::ate都是失败,
以ios::app|ios::out,如果没有文件则创建文件,如果有文件,则在文件尾追加
以ios::ate|ios::out打开,如果没有文件则创建文件,如果有,则清空文件。
以ios::ate|ios::out|ios::in打开,如果没有文件,则打开失败,有文件则定位到文件尾
可见:ios::app不能用来打开输入流,即不能和ios::in相配合
而ios::ate可以和ios::in配合,此时定位到文件尾;如果没有ios::in相配合而只是同ios::out配合,那么将清空原文件
(ios::ate|ios::in–>在原文件尾追加内容;ios::ate—>清空原文件,ios::out是默认必带的,可加上也可不加,对程序无影响)