C++学习进阶版(二):与文件相关的函数用法

目录

1、读取文件的指定行

(1)main函数中直接读

(2)封装成函数

① 无返回值类型

② 直接返回读取的内容

2、求文件的行数

3、文件内容读取成一个字符串


1、读取文件的指定行

(1)main函数中直接读

#include <iostream>
#include <fstream>
#include <string>int main() {// 要读取的行号,例如第5行int line_number = 5;int i = 0; std::ifstream file("G:/MyCode/c++/test.dump");if (file.is_open()) {std::string line;// 从1开始计数,因为行号通常是从1开始的while (std::getline(file, line)) {++i;if (i == line_number) {// 成功读取了目标行std::cout << "Line " << line_number << ": " << line << std::endl;break; // 找到目标行后退出循环}}if (i != line_number) {std::cerr << "Could not find line " << line_number << std::endl;}file.close();} else {std::cerr << "Unable to open file" << std::endl;}return 0;
}

(2)封装成函数

① 无返回值类型

#include <iostream>
#include <fstream>
#include <string>// 函数声明,只接受行号 n 作为参数
void readSpecificLineFromFile(int n);int main() {int line_number = 5; // 要读取的行号readSpecificLineFromFile(line_number);return 0;
}// 函数定义,读取并输出第 n 行的内容
void readSpecificLineFromFile(int n) {std::ifstream file("G:/MyCode/c++/test.dump");int current_line = 0;if (file.is_open()) {std::string line;while (std::getline(file, line)) {++current_line;if (current_line == n) {std::cout << "Line " << n << ": " << line << std::endl;file.close();return;}}std::cerr << "Could not find line " << n << std::endl;file.close();} else {std::cerr << "Unable to open file" << std::endl;}
}

② 直接返回读取的内容

#include <iostream>
#include <fstream>
#include <string>
using namespace std;// 函数声明,只接受行号 n 作为参数
std::string readLineFromFile(int n);int main() {int line_number = 5; // 要读取的行号std::string line= readLineFromFile(line_number);cout << line <<endl;return 0;
}// 函数定义,读取并输出第 n 行的内容
std::string readLineFromFile(int n) {std::ifstream file("G:/MyCode/c++/test.dump");int current_line = 0;std::string line;std::string lineContent;if (!file.is_open()) {std::cerr << "Unable to open file" << std::endl;return ""; // 返回空字符串表示文件无法打开}while (std::getline(file, line)) {++current_line;if (current_line == n) {lineContent = line;break;}}file.close(); // 确保文件被关闭return lineContent; // 返回找到的行内容,或空字符串表示未找到
}

2、求文件的行数

#include <iostream>
#include <fstream>
#include <string>// 函数声明
int countLines(const std::string& filename);int main() {int lineCount = countLines("1.dump");if (lineCount > 0) {std::cout << "The file '1.dump' has " << lineCount << " lines." << std::endl;} else {std::cerr << "The file '1.dump' could not be opened or is empty." << std::endl;}return 0;
}// 函数定义
int countLines(const std::string& filename) {std::ifstream file(filename);int lineCount = 0;// 检查文件是否成功打开if (file) {std::string line;// 逐行读取文件直到文件末尾while (std::getline(file, line)) {++lineCount;}} else {// 如果文件无法打开,返回0表示没有行lineCount = 0;}// 关闭文件file.close();// 返回文件的行数return lineCount;
}

3、文件内容读取成一个字符串

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <stdexcept>// 函数声明,读取文件并将其内容合并为一个字符串
std::string readAndConcatenateDumpFile(const std::string& filename);int main() {try {std::string filename = "1.dump";  // 文件路径std::string fileContents = readAndConcatenateDumpFile(filename);// 打印文件内容,这里仅打印前100个字符作为示例std::cout << "Contents of file '" << filename << "':" << std::endl;std::cout << fileContents << std::endl;} catch (const std::runtime_error& e) {std::cerr << "Error: " << e.what() << std::endl;return 1;  // 非正常退出,返回错误码}return 0;  // 正常退出
}// 函数定义,读取文件并将其内容合并为一个字符串
std::string readAndConcatenateDumpFile(const std::string& filename) {std::ifstream file(filename);if (!file.is_open()) {throw std::runtime_error("Failed to open the dump file.");}std::stringstream ss;std::string line;while (std::getline(file, line)) {ss << line;}file.close();return ss.str();
}

最近在用C++写指令文件的解码和状态机转换,其中的一些函数,供大家参考。

后续相关的会更新在文章中。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/641976.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

快速排序题目SelectK问题(力扣75.颜色分类、力扣215.数组中的第K个最大元素、面试题17.14最小K个数)

力扣75.颜色分类 给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums &#xff0c;原地对它们进行排序&#xff0c;使得相同颜色的元素相邻&#xff0c;并按照红色、白色、蓝色顺序排列。 我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 必须在不使用库内置的 sor…

C++:基础语法

一、命名空间 在C/C中&#xff0c;变量、函数和后面要学到的类都是大量存在的&#xff0c;这些变量、函数和类的名称将都存在于全局作用域中&#xff0c;可能会导致很多冲突。使用命名空间的目的是对标识符的名称进行本地化&#xff0c; 以避免命名冲突或名字污染&#xff0c;n…

Hindawi暴雷出局,Frontiers却积极整改,能否摘掉“水刊”标签?

【SciencePub学术】自从3月Hindawi暴雷后&#xff0c;MDPI和Frontiers也深受牵连&#xff0c;因其发文量太过猖獗&#xff0c;国人占比高&#xff0c;自引率高等因素&#xff0c;这些出版社旗下的期刊均被贴上“水刊”标签。 上期&#xff0c;小编已经详细介绍了MDPI期刊的口碑…

鸿蒙 harmonyos 线程 并发 总结 async promise Taskpool woker(三)多线程并发 Worker

Worker Worker是与主线程并行的独立线程。创建Worker的线程称之为宿主线程&#xff0c;Worker自身的线程称之为Worker线程。创建Worker传入的url文件在Worker线程中执行&#xff0c;可以处理耗时操作但不可以直接操作UI。 Worker主要作用是为应用程序提供一个多线程的运行环境…

目标检测算法是指什么?

一、目标检测算法是指什么&#xff1f; 目标检测算法是计算机视觉领域的一个重要分支&#xff0c;它旨在识别和定位图像中的目标对象。以下是目标检测算法的相关内容&#xff1a; 目标检测的核心问题&#xff1a;目标检测需要解决的两个核心问题是“目标是什么”和“目标在哪里…

如何加盟共享wifi项目?了解套路有哪些?

自共享wifi项目推出在市场火爆后&#xff0c;各路资本都看到了该项目的广阔前景&#xff0c;纷纷开始研发程序&#xff0c;想要趁机分一杯羹。但对于普通人而言&#xff0c;独立研发程序显然不大现实&#xff0c;于是&#xff0c;共享wifi项目如何加盟便成为了绝大多数人最为关…

java异常的捕获

Java内置了一套异常处理机制&#xff0c;总是使用异常来表示错误。 一,使用try……catch来捕获错误 异常是一种class&#xff0c;因此它本身带有类型信息。异常可以在任何地方抛出&#xff0c;但只需要在上层捕获&#xff0c;这样就和方法调用分离了&#xff1a; try {Strin…

机器人自动驾驶时间同步进阶

0. 简介 之前时间同步也写过一篇文章介绍机器人&自动驾驶中的时间同步。在最近的学习中发现一些额外需要阐述学习的内容&#xff0c;这里就再次写一些之前没写到的内容。 1. NTP NTP 是网络时间协议&#xff0c;用来同步网络中各计算机时间的协议&#xff0c;把计算机的时…

[计算机效率] 网站推荐:网盘资源类

4.6 网盘资源类 在数字化时代&#xff0c;网盘资源搜索已成为我们日常生活和工作中不可或缺的一部分。无论是寻找工作资料、学习素材&#xff0c;还是娱乐资源&#xff0c;一个高效、可靠的网盘资源搜索网站都能为我们节省大量时间。今天&#xff0c;我将为大家推荐几个优秀的…

【C++类和对象】日期类的实现

&#x1f49e;&#x1f49e; 前言 hello hello~ &#xff0c;这里是大耳朵土土垚~&#x1f496;&#x1f496; &#xff0c;欢迎大家点赞&#x1f973;&#x1f973;关注&#x1f4a5;&#x1f4a5;收藏&#x1f339;&#x1f339;&#x1f339; &#x1f4a5;个人主页&#x…

华为公司战略规划和落地方法之五看三定工具解析【PPT图片】(内含超级福利)

导言 华为公司最厉害之处就是战略上的高举高打&#xff0c;“吹过的牛都实现了”。支撑华为公司战略从规划到落地的主要工具很多&#xff0c;其中“五看三定”是战略规划时最核心的方法之一。本资料将介绍五看三定的核心精髓。欢迎学习&#xff01; 本材料结合谢宁老师专著《华…

数据结构之顺序表的实现(C语言版)

Hello, 大家好&#xff0c;我是一代&#xff0c;今天给大家带来有关顺序表的有关知识 所属专栏&#xff1a;数据结构 创作不易&#xff0c;望得到各位佬们的互三呦 一.前言 1.首先在讲顺序表之前我们先来了解什么是数据结构 数据结构是由“数据”和“结构”两词组合⽽来。 什…