【问题标题】:C++ how to add/subtract tellp(), tellg() returnC++如何加/减tellp(),tellg()返回
【发布时间】:2013-05-29 23:02:45
【问题描述】:

假设我想得到两个 tellp() 输出之间的差异(以 int 为单位)。

如果写入一个大文件,tellp() 的输出可能会很大,因此将其存储在 long long 中是不安全的。有没有一种安全的方法来执行这样的操作:

ofstream fout;
fout.open("test.txt",ios::out | ios::app);
int start = fout.tellp();
fout<<"blah blah "<<100<<","<<3.14;
int end = fout.tellp();
int difference = end-start;

在这里,我知道 end 和 start 之间的差异绝对可以放在 int 中。但是结束和开始本身可能非常庞大。

【问题讨论】:

  • long long 对于几个 Exabytes 就足够了。您打算支持多大的文件?
  • 不得不将它转换成 long long 看起来很丑,这种返回类型没有内置的加法/减法?
  • 文件最大为 1GB。为此,似乎很长就足够了?
  • 对于 1GB,long 确实足够了。
  • 1GB 对于每个人来说应该足够了。

标签: c++ iostream ofstream


【解决方案1】:

ofstream::tellp(和ifstream::tellg)的返回类型是char_traits&lt;char&gt;::pos_type。除非你真的需要你的最终结果是int,否则你可能想在整个过程中使用pos_type。如果您确实需要将最终结果作为int,您可能仍希望将中间值存储在pos_types 中,然后进行减法并将结果转换为int

typedef std::char_traits<char>::pos_type pos_type;

ofstream fout;
fout.open("test.txt",ios::out | ios::app);
pos_type start = fout.tellp();
fout<<"blah blah "<<100<<","<<3.14;
pos_type end = fout.tellp();
int difference = int(end-start);
// or: pos_type difference = end-start;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 2012-08-28
    • 2023-02-04
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多