将整个文件读入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 );
  1. 获取文件的大小,就像你所做的。
  2. 分配char的数组来保存内容
  3. 使用istream::read将整个文件读入char数组
  4. 创建使用char数组的istringstream。使用它解析数据。
  5. 释放char的数组。

如果您想遵循此策略,请确保以二进制模式打开文件。谢谢@ooga。

你的结论无效。

如果>>操作符是一个开销,它们在操作字符串时也会有相同的开销,并且在处理之前读取整个文件只是增加了延迟,即浪费时间和空间。

你不需要这样做。只要确保在fstream.

上有足够的缓冲即可。