C++ – 最简单的将文本文件的内容一次性读取到std::string的方法
1 C++将文本文件一次性读取到std::string的方法
包含头文件:
#include <fstream>
#include <iostream>
读取代码如下:
std::ifstream in("test.txt", std::ios::in);
std::istreambuf_iterator<char> beg(in), end;
std::string strdata(beg, end);
in.close();
strdata即为存储该文本文件所有内容的string。
该方法只有四行代码即可完成文本文件的读取,不需要再一行一行的读了!
2 使用文件流的方式
#include <iostream>
#include <fstream>
std::string ReadFileToString(const std::string& file_path)
{
int fileLength = 0;
std::ifstream inFile(file_path, std::ios::binary);
if (!inFile.is_open())
{
inFile.close();
}
// 跳到文件尾
inFile.seekg(0, std::ios::end);
// 获取字节长度
fileLength = inFile.tellg();
// 跳到文件开头
inFile.seekg(0, std::ios::beg);
char* buffer = new char[fileLength];
// 读取文件
inFile.read(buffer, fileLength);
std::string result_str(buffer, fileLength);
delete[] buffer;
inFile.close();
return result_str;
}
int main()
{
std::cout << "读取的文件内容为:" << ReadFileToString("helloworld.txt") << std::endl;
return 0;
}
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – 最简单的将文本文件的内容一次性读取到std::string的方法
原文链接:https://www.stubbornhuang.com/902/
发布于:2020年08月21日 23:00:14
修改于:2023年06月26日 22:18:25
当前分类随机文章推荐
- GCC - -fpic、-fPIC、-fpie、-fPIE编译选项的作用和区别 阅读261次,点赞0次
- C++ - int转string方法总结 阅读6988次,点赞0次
- C++ - 速通nlohmann json,nlohmann json使用教程 阅读177次,点赞0次
- C++ – Unicode编码下的全角字符转半角字符 阅读2740次,点赞0次
- C++11 - 使用std::thread::join()/std::thread::detach()方法需要注意的点 阅读3562次,点赞0次
- C++ - Jni中的GetByteArrayElements和GetByteArrayRegion的区别和使用示例 阅读4622次,点赞0次
- C++11 - 委托机制的实现TinyDelegate 阅读1726次,点赞0次
- C++11 - std::shared_ptr初始化的几种方式 阅读7505次,点赞2次
- C++ - C++实现Python numpy的矩阵维度转置算法,例如(N,H,W,C)转换为(N,C,H,W) 阅读5095次,点赞4次
- C++STL容器 - std::map容器修改、元素操作总结 clear,insert,emplace,erase,swap,merge,extract,insert_or_assign等 阅读2255次,点赞0次
全站随机文章推荐
- 资源分享 - Game AI Pro - Collected Wisdom of Game AI Professionals 英文高清PDF下载 阅读2058次,点赞0次
- 资源分享 - Handbook of Discrete and Computational Geometry, Third Edition英文高清PDF下载 阅读3578次,点赞0次
- nginx - 封禁IP和封禁IP段 阅读31次,点赞0次
- WordPress - 用户修改密码/邮箱时禁止向管理员/用户发送通知邮件 阅读1143次,点赞0次
- TensorRT - Windows下TensorRT下载与配置 阅读2027次,点赞0次
- TensorRT - 使用C++ SDK出现无法解析的外部符号 "class sample::Logger sample::gLogger"错误 阅读688次,点赞0次
- Modern OpenGL - GLSL着色语言1:OpenGL着色器简介 阅读2977次,点赞0次
- TensortRT - 转换模型出现Could not locate zlibwapi.dll. Please make sure it is in your library path!错误 阅读1203次,点赞0次
- 深度学习 - CNN中卷积层、池化层、全连接层的输出参数大小的计算 阅读1002次,点赞1次
- Pytorch - 修改Pytoch中torchvision.models预置模型的方法 阅读389次,点赞0次
评论
169