将整个文件读入stringstream
Reading entire file into stringstream
本文关键字:stringstream 文件 更新时间:2023-10-16
所以,我想通过某种流解析一个文件,我确实可以简单地使用ifstream类,但问题是我的目标是性能和所有那些>>操作符的ifstream类可能真的会减慢我的程序。所以我想到了一个想法,以某种方式将整个文件读入std::stringstream,然后用stringstream解析文件。我想做这样的事情,但是我不能让它工作:
std::ifstream fin( p_Filename.c_str( ) );
fin.seekg( 0, std::ifstream::end );
int fileSize = static_cast<int>( fin.tellg( ) );
fin.seekg( 0, std::ifstream::beg );
std::stringstream ss;
ss.str( ).resize( fileSize );
fin.read( const_cast<char*>( ss.str( ).c_str( ) ), fileSize );
- 获取文件的大小,就像你所做的。
- 分配
char
的数组来保存内容 - 使用
istream::read
将整个文件读入char
数组 - 创建使用
char
数组的istringstream
。使用它解析数据。 释放
char
的数组。
如果您想遵循此策略,请确保以二进制模式打开文件。谢谢@ooga。
你的结论无效。
如果>>
操作符是一个开销,它们在操作字符串时也会有相同的开销,并且在处理之前读取整个文件只是增加了延迟,即浪费时间和空间。
你不需要这样做。只要确保在fstream.
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- C++ - 使用 stringstream 对象从外部 txt 文件中的句子中读取字符串和整数
- 使用stringstream和ofstream编写长日志文件
- 使用"ifstream"、"stringstream"和"rdbuf()"将文件内容读取为字符串时如何检查I/O错误?
- 如何将数据从stringstream写入文件(CPP)
- 如何将数据从stringstream打印到文件
- 将整个文件读入stringstream
- 用于在文件中写入的Stringstream或ostringstream
- 如何有一个正确的路径文件读取它到stringstream