C++ find size of ofstream

大憨熊 提交于 2019-12-12 09:54:05

问题


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);

回答1:


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.




回答2:


Use ostream::tellp(), before and after




回答3:


fout::tellp() will give you position of the next byte to be written to.




回答4:


You can get the current position using tellg or tellp:

fin.tellg();  // postition of "get" in istream or iostream (fstream)
fout.tellp(); // position of "put"  in ostream or iostream (fstream)


来源:https://stackoverflow.com/questions/16825055/c-find-size-of-ofstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!