【问题标题】:Internal buffer used by standard input stream (pubsetbuf)标准输入流使用的内部缓冲区 (pubsetbuf)
【发布时间】:2019-05-23 21:49:30
【问题描述】:

我正在尝试设置输入流的内部缓冲区,但我在 C++17 中的实现没有为 istringstream 实现 pubsetbuf()。

我尝试了一些其他技术,但它们速度慢或复制原始缓冲区。我正在寻找一种不进行任何复制的快速方法。

它与这个关于输出流的问题密切相关: Setting the internal buffer used by a standard stream (pubsetbuf)

我已经密切关注它,但输入流的缓冲区仍未初始化/为空。

// Modified template from the other question about an output stream.
// This is for an input stream, but I can't get it to work.
template <typename char_type>
struct istreambuf : public std::basic_streambuf<char_type, std::char_traits<char_type> >
{
    istreambuf(char_type* buffer, std::streamsize buffer_length)
    {
        // Set the "put" pointer to the start of the buffer and record its length.
        this->setp(buffer, buffer + buffer_length);
    }
};

int main()
{
    ifstream infile(FILENAME, std::ifstream::binary);
    if (!infile.is_open())
    {
        cerr << endl << "Failed to open file " << FILENAME << endl;
        return 0;
    }

    // Works, but slow.
    //istringstream local_stream;
    //local_stream << infile.rdbuf();

    // Works, but creates a copy.
    //istringstream local_stream(&buffer[0]);  

    // Works, but creates a copy.
    //local_stream.str(&buffer[0]);

    // Read entire file into buffer.
    infile.seekg(0, std::ios::end);
    streampos length = infile.tellg();
    infile.seekg(0, std::ios::beg);
    vector<char> buffer(length);
    //char* buffer = new char[length];
    infile.read(&buffer[0], length);

    // Doesn't work, but should point to original.
    // It returns "this" (does nothing).
    //local_stream.rdbuf()->pubsetbuf(&buffer[0], length);  

    // Works, but deprecated in C++98.
    //std::istrstream local_stream(&buffer[0]);  
    //local_stream.rdbuf()->pubsetbuf(&buffer[0], length);

    // I followed the example in the other question about an output stream,
    // but I modified for an input stream. I can't get it to work. Any ideas?
    istreambuf<char> istream_buffer(&buffer[0], length);
    istream local_stream(&istream_buffer);

    string str1, str2;
    while (local_stream >> str1 && local_stream >> str2)
    {
        . . .
    }
}

【问题讨论】:

  • 这个问题没有说明问题是什么。诸如“没有多大成功”和“无法让它发挥作用”之类的描述含糊不清,没有帮助。目前形式的这个问题不太可能在未来对某人有所帮助。我会要求澄清,但看起来问题不再是问题。
  • 感谢您的建议。为了清楚起见,我对其进行了编辑。

标签: c++ istream istringstream


【解决方案1】:

我已经解决了!找出差异。

模板 
struct istreambuf: public std::basic_streambuf
{
    istreambuf(char_type* 缓冲区,std::streamsize 缓冲区长度)
    {
        // 将“put”指针设置为缓冲区的开头并记录其长度。
        //this->setp(buffer, buffer + buffer_length);

        // 将“get”指针设置为缓冲区的开头、下一项,并记录其长度。
        this->setg(缓冲区,缓冲区,缓冲区 + 缓冲区长度);
    }
};

我需要设置“get”指针,而不是“put”指针。现在效果很好。

【讨论】:

    猜你喜欢
    • 2010-12-02
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多