0

下面是我正在运行的代码和相应的输出。

    #include<iostream>
    #include <sstream>
    #include <strstream>
    #include <streambuf>

    template <typename char_type>
struct ostreambuf : public std::basic_streambuf<char_type,std::char_traits<char_type> >
{
 ostreambuf(char_type* buffer, std::streamsize bufferLength)
{
    // set the "put" pointer the start of the buffer and record it's length.
    setp(buffer, buffer + bufferLength);
}
};


int main()            
{
 char strArr[]    = "Before-1";
 char stringArr[] = "Before-2";

 std::strstream strStream(strArr,sizeof(strArr));

 ostreambuf<char> ostreamBuffer(stringArr, sizeof(stringArr));
 std::ostream stringStream(&ostreamBuffer);

  const std::streampos posStringBefore = stringStream.tellp();

   std::cout << "Before: "
                                    << "strArr = " 
                                    << strArr 
                                    << " & "
                                    << "stringArr = "
                                    << stringArr
                                    << std::endl;

            std::cout << "Before: " << "posStringBefore = "
                                    << posStringBefore
                                    << std::endl;

            // -------------------------
            strStream << "After-1";
            stringStream << "After-2";
            const std::streampos posStringAfter = stringStream.tellp(); 

            std::cout << "After : "
                                    << "strArr = " 
                                    << strArr 
                                    << " & "
                                    << "stringArr = "
                                    << stringArr
                                    << std::endl;

            std::cout << "After : " << "posStringAfter = "
                                    << posStringAfter
                                    << std::endl;



            return 0;
}

这是 VS2010 上的 o/p :

 Before: strArr = Before-1 & stringArr = Before-2
 Before: posStringBefore = -1
 After : strArr = After-11 & stringArr = After-22
 After : posStringAfter = -1

参考链接 设置标准流使用的内部缓冲区(pubsetbuf)

如何获取创建的 std::ostream 对象的大小?

4

1 回答 1

0

它不会给你一个“错误的”输出/价值。tellp使用rdbuf()->pubseekoffwhich 将呼叫中继到virtual seekoff. basic_streambuf实现只是按照 C++ 标准中的-1定义返回。你需要在你的ostreambuf类中为这个方法提供一个自己的实现。

参见cppreference:basic_streambuf::pubseekof

于 2013-04-02T12:22:24.483 回答