Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ find size of ofstream

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);
like image 648
user788171 Avatar asked Dec 16 '22 10:12

user788171


2 Answers

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.

like image 150
Jerry Coffin Avatar answered Jan 01 '23 17:01

Jerry Coffin


Use ostream::tellp(), before and after

like image 25
AlexK Avatar answered Jan 01 '23 17:01

AlexK