C++ std::streambuf 小结
介绍
我们看到的 std:cin
, std:cout
都是对 streambuf
的封装。你可以通过 std::cout.rdbuf ()
来获取,也可以通过 std::cout.rdbuf (&newbuf)
来置换。
例子
重定向标准输出
让我们看看如何把 std::cout
重定向到一个文件。
ofstream:输出文件流,用于创建文件并向文件写入信息。
tests/streambuf.cpp
#include <ctime>
#include <fstream>
#include <iostream>
int
main ()
{
std::ofstream ofs;
ofs.open ("log.txt", std::ofstream::out | std::ofstream::app);
std::cout.rdbuf(ofs.rdbuf());
char const *message = "Hello, world!";
std::cout << message;
ofs.close ();
return 0;
}
std::ofstream::app
表示追加模式。具体参考 ofstream::open - C++ Reference (cplusplus.com)
常用的函数
Input functions (get):
-
Get number of characters available to read (public member function )
-
Advance to next position and get character (public member function )
-
Get current character and advance to next position (public member function )
-
Get current character (public member function )
-
Get sequence of characters (public member function )
-
Put character back (public member function )
-
Decrease current position (public member function )
Output functions (put):
-
Store character at current put position and increase put pointer (public member function )
-
Put sequence of characters (public member function )
需要注意的是 uflow ()
,如果它返回 EOF,则说明读到文件尾部。
printf
上面的例子虽然可以观察到 cout
输出到文件,但是如果使用 printf
则不会看到效果。要想重定向 printf,思路:
- 使用 freopen
- 使用自定义函数,覆盖 printf 函数
- 使用 fprintf