C++文件处理(一):读/写txt文件
C++文件处理与C语言不同,C++文件处理使用的是:流(stream)
C++头文件fstream定义了三个类型来支持文件IO
- ifstream从一个给定文件中读取数据
- ofstream向一个给定文件写入数据
- fstream可以读写文件
这些类型提供的操作与我们之前已经使用过的cin和cout操作一样。特别是,我们可以使用IO运算符(>>和<<)来读写文件,也可使用getline从一个ifstream中读取数据。

图1. fstream特有的操作(图片来源于参考[1])
一、读txt文件
现有cameras.txt文件,内容如下
读取txt文件,并逐行打印
# Camera list with one line of data per camera:
# CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]
# Number of cameras: 1
0 PINHOLE 6220 4141 3430.27 3429.23 3119.2 2057.75
// Author: Programmer ToddyQi
// Date: 2020-02-12
#include <iostream>
#include <fstream> // 头文件 For both fstream and ifstream
#include <string>
using namespace std;
int main() {
string path = "./cameras.txt";
ifstream in_file(path, ios::in); //按照指定mode打开文件
// is_open()函数返回一个bool值,指出与in_file关联的文件是否成功打开且未关闭
if (in_file.is_open()) { // 或者if (in_file)
cout << "Open File Successfully" << endl;
string line;
while(getline(in_file, line)) {
cout << line << endl;
}
} else {
cout << "Cannot Open File: " << path << endl;
getchar();
return EXIT_FAILURE;
}
in_file.close(); // 关闭与in_file绑定的文件,返回void
getchar();
return EXIT_SUCCESS;
}

图2. 实验运行结果
二、写txt文件
main()函数如下,main()函数之前的部分同上
int main()
{
string path = "./log.txt";
ofstream out_file(path, ios::out | ios::app); //按照指定mode打开文件
// ofstream out_file(path, ios::out);
if (out_file.is_open()) {
cout << "Open File Successfully" << endl;
out_file << "Have a Nice Day!" << endl;
} else {
cout << "Cannot Open File: " << path << endl;
getchar();
return EXIT_FAILURE;
}
out_file.close();
getchar();
return EXIT_SUCCESS;
}

图3. 实验运行结果
Code is Here: 点击查看详细内容 TODO
// 解析cameras.txt文件
void Reconstruction::ReadCamerasText(const std::string& path) {
cameras_.clear();
std::ifstream file(path);
CHECK(file.is_open()) << path;
std::string line;
std::string item;
while (std::getline(file, line)) {
StringTrim(&line);
if (line.empty() || line[0] == '#') {
continue;
}
std::stringstream line_stream(line);
class Camera camera;
// ID
std::getline(line_stream, item, ' ');
camera.SetCameraId(std::stoul(item));
// MODEL
std::getline(line_stream, item, ' ');
camera.SetModelIdFromName(item);
// WIDTH
std::getline(line_stream, item, ' ');
camera.SetWidth(std::stoll(item));
// HEIGHT
std::getline(line_stream, item, ' ');
camera.SetHeight(std::stoll(item));
// PARAMS
camera.Params().clear();
while (!line_stream.eof()) {
std::getline(line_stream, item, ' ');
camera.Params().push_back(std::stold(item));
}
CHECK(camera.VerifyParams());
cameras_.emplace(camera.CameraId(), camera);
}
}
参考
- C++ Primer 第五版
- Reading from a Text File
C++文件处理(一):读/写txt文件的更多相关文章
- 【学习总结】GirlsInAI ML-diary day-15-读/写txt文件
[学习总结]GirlsInAI ML-diary 总 原博github链接-day15 认识读/写txt文件 路径: 绝对路径:文件在电脑中的位置 相对路径:下面会用到 1-准备 新建一个 pytho ...
- WPF: 读取XPS文件或将word、txt文件转化为XPS文件
读取XPS格式文件或将doc,txt文件转化为XPS文件,效果图如下: 1.XAML页面代码: <Window x:Class="WpfWord.MainWindow" xm ...
- WFP: 读取XPS文件或将word、txt文件转化为XPS文件
读取XPS格式文件或将doc,txt文件转化为XPS文件,效果图如下: 1.XAML页面代码: <Window x:Class="WpfWord.MainWindow" ...
- 读取同一文件夹下多个txt文件中的特定内容并做统计
读取同一文件夹下多个txt文件中的特定内容并做统计 有网友在问,C#读取同一文件夹下多个txt文件中的特定内容,并把各个文本的数据做统计. 昨晚Insus.NET抽上些少时间,来实现此问题,加强自身的 ...
- C++实现从一个文件夹中读出所有txt文件
前段时间做项目需要读取一个文件夹里面所有的txt文件,查询资料后得到以下实现方法:首先了解一下这个结构体struct _finddata_t { unsigned attrib; t ...
- MATLAB实例:新建文件夹,保存.mat文件并保存数据到.txt文件中
MATLAB实例:新建文件夹,保存.mat文件并保存数据到.txt文件中 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 用MATLAB实现:指定路径下 ...
- C#做一个写txt文件流的测试,为什么配置低的机器写入的还快
测试机:笔记本i7 8G 固态硬盘 由于采取读码写入txt方式, 读码频率挺高,文件名为日期格式,当前采用每次读码打开文件写入的方式, 为什么没用sb,因为怕断电情况的数据丢失.所以采取每条存入的方式 ...
- day9 python学习 文件的操作 读 写 seek
文件的操作 1 文件的打开操作: 文件句柄 = open('文件路径', '模式') f=open('wangyakun','a+',encoding='utf-8') #文件名, 如果是绝对路径 ...
- .Net写txt文件-简单的记录执行日志信息代码
在执行一些批量操作时,想记录一些执行日志信息,越简单方便越好啊.提供一个常用的简单方法,将信息记录在txt文件里: public static void log(string content, str ...
随机推荐
- python笔记15
今日内容 模块知识 内置模块 time datetime json 其他 内容回顾 & 作业题 重要知识点 构造字典和函数对应关系,避免重复的if else a=1 b=2 ==> a, ...
- openstack 架构
openstack 概念架构: openstack逻辑架构 常见的架构:
- permission denied (publickey)问题的解决和向github添加ssh key
使用ssh key这种方式进行clone ,pull github上面的项目,使用 git clone或者git pull origin master出现permission denied (publ ...
- Rust语言Actix-web框架连接Redis数据库
Rust语言Actix-web框架连接Redis数据库 actix-web2.0终于发布了,不再是测试版本,基于actor系统再加上异步支持,使得actix-web成为了目前响应速度最快的服务器框架, ...
- Codeforces_723_D
http://codeforces.com/problemset/problem/723/D dfs找出每个湖,保存坐标和大小,按大小排序,填充湖即可,注意湖的数量最多会有1250个. #includ ...
- CCF_ 201512-2_消除类游戏
水平方向遍历一次,竖直方向遍历一次,将需要删除的位置标志入一个数组,最后比较输出即可. #include<cstdio> #include<iostream> using na ...
- HDU_2191_多重背包
http://acm.hdu.edu.cn/showproblem.php?pid=2191 简单多重背包题. #include<iostream> #include<cstdio& ...
- Springboot笔记(二)整合
1.整合Freemarker 一种模板引擎,前端渲染模板的,类似于EL,jsp,不过比前两个好用 导入很简单 pom.xml <dependency> <groupId>o ...
- 【大白话系统】MySQL 学习总结 之 缓冲池(Buffer Pool) 的设计原理和管理机制
一.缓冲池(Buffer Pool)的地位 在<MySQL 学习总结 之 InnoDB 存储引擎的架构设计>中,我们就讲到,缓冲池是 InnoDB 存储引擎中最重要的组件.因为为了提高 M ...
- Wannafly挑战赛5 A珂朵莉与宇宙 前缀和+枚举平方数
Wannafly挑战赛5 A珂朵莉与宇宙 前缀和+枚举平方数 题目描述 给你一个长为n的序列a,有n*(n+1)/2个子区间,问这些子区间里面和为完全平方数的子区间个数 输入描述: 第一行一个数n 第 ...