C++ find size of ofstream

user788171 picture user788171 · May 30, 2013 · Viewed 9.4k times · Source

I have code that currently does something like the following:

ofstream fout;
fout.open("file.txt");
fout<<"blah blah "<<100<<","<<3.14;
//get ofstream length here
fout<<"write more stuff"<<endl;

Is there a convenient way to find out the length of that line that is written at the stage I specified above? (in real life, the int 100 and float 3.14 are not constant and can change). Is there a good way to do what I want?

EDIT: by length, I mean something that can be used using fseek, e.g.

fseek(pFile, -linelength, SEEK_END);

Answer

Jerry Coffin picture Jerry Coffin · May 30, 2013

You want tellp. This is available for output streams (e.g., ostream, ofstream, stringstream).

There's a matching tellg that's available for input streams (e.g., istream, ifstream, stringstream). Note that stringstream supports both input and output, so it has both tellp and tellg.

As to keeping the two straight, the p means put and the g means get, so if you want the "get position" (i.e., the read position) you use tellg. If you want the put (write) position, you use tellp.

Note that fstream supports both input and output, so it includes both tellg and tellp, but you can only call one of them at any given time. If the most recent operation was a write, then you can call tellp. If the most recent operation was a read, you can call tellg. Otherwise, you don't get meaningful results.