C++:获取使用ofstream时打印的字符数
C++: get number of characters printed when using ofstream
C fprintf()
函数返回打印的字符数。使用 ofstream
写入文件时,C++中是否有类似的功能?如果可能的话,我对与 C++03 兼容的解决方案感兴趣。
例如:
ofstream file("outputFile");
file << "hello";
// Here would I like to know that five characters were printed.
file << " world";
// Here I would like to know that six characters were printed.
您要查找的是tellp()
。
你可以这样使用它:
ofstream file("outputFile");
auto pos1 = file.tellp();
file << "hello";
auto pos2 = file.tellp();
std::cout << pos2 - pos1 << std::endl;
查找操作相当昂贵(主要是因为它们需要准备流才能在读取和写入之间切换(。我个人宁愿使用提供计数的过滤流缓冲区,例如:
class countbuf: public std::streambuf {
std::streambuf* sbuf;
std::size_t count;
char buffer[256];
int overflow(int c) {
if (c != std::char_traits<char>::eof()) {
*this->pptr() = c;
this->pbump(1);
}
return this->sync() == -1
? std::char_traits<char>::eof()
: std::char_traits<char>::not_eof(c);
}
int sync() {
std::size_t size(this->pptr() - this->pbase());
this->count += size;
this->setp(this->buffer, this->buffer + 256);
return size == this->sbuf->sputn(this->pbase(), this->pptr() - this->pbase())
? this->sbuf->pubsync(): -1;
}
public:
countbuf(std::streambuf* sbuf): sbuf(sbuf), count() {
this->setp(buffer, buffer + 256);
}
std::size_t count() const { return count + this->pptr() - this->pbase(); }
std::size_t reset() const {
std::size_t rc(this->count());
this->sync();
this->count = 0;
return rc;
}
};
获得此流缓冲区后,只需安装到std::ostream
中(并可能将构造打包到自定义流类中(:
countbuf sbuf(std::cout.rdbuf()); // can't seek on this stream anyway...
std::ostream out(&sbuf);
out << "hello!n" << std::flush;
std::cout << "count=" << out.reset() << 'n';
相关文章:
- 打印字符数组地址的正确方法
- c ++控制台应用程序,如何在控制台外部打印字符
- 无法使用 swprintf 在 WCHAR* 中打印字符*
- 存储和打印字符,但输出不是预期的
- 如何使 printf 以与 NSLog 相同的方式打印字符缓冲区?
- 在带有 (void*) 强制转换的字符串中打印字符的内存地址
- C++无法打印字符变量
- 无法打印字符向量C++向量
- 为什么在编辑 fastq 文件并将输出写入新的 fastq 文件时引入不可打印字符?
- C :如何询问文件名并打印字符数组
- 循环中的 Cout 不会按定义的字符逐个打印字符
- (C++) 打印字符数组字符串的单词时出现问题
- 用putchar在屏幕上打印字符
- 在C 中使用继续语句的打印字符
- 在 for 循环 c++ 中打印字符
- 使用while和if递归打印字符
- 打印字符数组 c++
- 如何使用Xcode中的Unicode打印字符╔(和其他字符)
- cout.put() 是否推荐使用 cout<< 打印字符
- C++ 中的密码 |打印字符后删除字符