0

I am writing a c++ program to write to a text file of a specified size. I initially create a text file of size specified say 2 KB, I want to keep writing to this file till the 2 KB limit is reached and that point notify the user. I am not sure what the best way is. I am looking for a cross platform solution. Would something like libevent (http://libevent.org/) be good for this or am I missing something simpler.

Any advice/help greatly appreciated.

Thanks

ababeel
  • 435
  • 1
  • 8
  • 25

1 Answers1

4
#include <fstream>

int main()
{
    std::ofstream ofs("output.img", std::ios::binary | std::ios::out);
    ofs.seekp((2<<10) - 1);
    ofs.write("", 1);
}
  • If you want to detect filepos, you could use std::ofstream::tellp()
  • alternatively, sync + stat will be able to get up-to-date filesize without re-opening the file
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
sehe
  • 374,641
  • 47
  • 450
  • 633
  • @ababeel: then you've also written to it. – Fred Foo Nov 22 '11 at 00:21
  • @ababeel: don't stop reading at the code. The rest of the answer contains hints on how to monitor file size! – sehe Nov 22 '11 at 00:23
  • I am going blind or low blood sugar (i dont know which). Thanks I had not read the last 2 lines. My apologies. – ababeel Nov 22 '11 at 00:36
  • A little more help please I guess I cannot get the file size while I am writing to it. e.g. I am doing -> while(i++ < 1024) { outfile << 'A'; if (fileSize(file) > 1024) break; }. The fileSize seems to be zero. I tried getting the fileSize using various methods, stat, ifstream::tell etc. Please advise thanks. – ababeel Nov 23 '11 at 01:47
  • `stat` requires a fsync (so the filesystem driver doesn't just tell you the last known size) and ifstream::tell doesn't sound right; You are _writing_ so an `ostream::tellp` would seem in order. Don't forget to `ofs << std::flush`. **Out of the box** why don't you look at memory mapping? – sehe Nov 23 '11 at 01:54