【发布时间】:2009-10-18 08:43:53
【问题描述】:
有人可以写一些示例代码来解释这个概念吗? 我知道缓冲流的用途,但我也想知道如何实现它。
提前致谢!
【问题讨论】:
-
什么意思? stringstream 是如何实现的,或者 std::cin/cout?
-
缓冲流,就像otl中的流
标签: c++ mfc bufferedstream
有人可以写一些示例代码来解释这个概念吗? 我知道缓冲流的用途,但我也想知道如何实现它。
提前致谢!
【问题讨论】:
标签: c++ mfc bufferedstream
您可以查看您平台的实现、C++ 标准或"Standard C++ IOstreams and Locales" by Angelika Langer and Klaus Kreft。
为相当长的学习曲线做好准备。流是古老而复杂的事情。 (弗朗西斯·格拉斯伯罗:"I have very few doubts that I/O libraries are amongst the most difficult aspects of any language.")
【讨论】:
对于“输入”流的示意图:
class BufferedInputStream
{
public:
BufferedInputStream(SomeExternalDevice d)
: m_Device(d),
m_Current(m_Buffer),
m_End(m_Buffer)
{}
char get(){
if (!IsDataAvailableInBuffer()){
ReadAChunkFromDiskAndPutItInBuffer();
}
return PopByteFromBuffer();
}
private:
bool IsDataAvailableInBuffer()const{
return m_Current != m_End;
}
void ReadAChunkFromDiskAndPutItInBuffer(){
// Buffer must be empty
assert(!IsDataAvailableInBuffer());
// Read bytes from the device
bytes_read = Read(m_Device, m_Buffer, BufferSize);
// Reposition the "begin" and "end" pointers
m_Current = m_Buffer;
m_End = m_Buffer + bytes_read;
}
char PopByteFromBuffer(){
assert(IsDataAvailableInBuffer());
return *m_Current++;
}
// For example, an OS file handle
SomeExternalDevice m_Device;
// The buffer itself
char m_Buffer[BufferSize];
// Begin of buffer contents
char* m_Current;
// End of buffer contents
char* m_End;
};
这样,数据以缓冲区大小的块从磁盘读取,并且大多数对“get()”的调用不必以对操作系统的调用结束,因为它们可以简单地从缓冲区。
【讨论】:
看看 STL 的实现 sstream 和 sstream.tcc(链接到 SGI STL 实现)。
stringstream 基类是basic_stringstream,它实现了basic_iostream 接口。
// [27.7.4] Template class basic_stringstream
/**
* @brief Controlling input and output for std::string.
*
* This class supports reading from and writing to objects of type
* std::basic_string, using the inherited functions from
* std::basic_iostream. To control the associated sequence, an instance
* of std::basic_stringbuf is used, which this page refers to as @c sb.
*/
有一个派生自basic_streambuf 的基类basic_stringbuf。这保存了缓冲区。
// [27.7.1] template class basic_stringbuf
/**
* @brief The actual work of input and output (for std::string).
*
* This class associates either or both of its input and output sequences
* with a sequence of characters, which can be initialized from, or made
* available as, a @c std::basic_string. (Paraphrased from [27.7.1]/1.)
*
* For this class, open modes (of type @c ios_base::openmode) have
* @c in set if the input sequence can be read, and @c out set if the
* output sequence can be written.
*/
【讨论】: