2

I've been using std::ofstream for writing purposes quite a bit. I open the file, do some operations based on certain conditions and close it.

Let's say that later I want to check if anything is really written into the file or not. There is not is_emtpy() kind of simple check available with std::ofstream.

One way I thought is of using the stat way which is independent of std::ofstream.

Wonder how do everyone else do it?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Hemant Bhargava
  • 3,251
  • 4
  • 24
  • 45
  • 2
    One way is to open it for reading, seek to the end, and check the position (which will equal the size of the file). – Some programmer dude Jul 23 '19 at 18:01
  • 3
    If *you* are writing to it, and you handle errors properly, then you know it already, since `write()` returns the bytes written. – rustyx Jul 23 '19 at 18:03
  • 1
    Hemant, your question is already answered, check the duplicates! Next time, you can save yourself some time and search a bit before asking.. I searched for "check if file is empty c++" and got the results right away. :D Hope that helps.. :) – gsamaras Jul 23 '19 at 18:10
  • @gsamaras, He he. My question was to know if it could be done with std::ofstream though. – Hemant Bhargava Jul 23 '19 at 18:16
  • Hemant my sincere apologies. I misunderstood your question, re-opened - my intentions were good. Good luck finding an answer! – gsamaras Jul 23 '19 at 18:23
  • 2
    Note `tellp` just before closing? – Daniel Sęk Jul 23 '19 at 19:29
  • [std::filesystem::file_size](https://en.cppreference.com/w/cpp/filesystem/file_size) could be used instead of `stat` if you are using C++17. – Ted Lyngmo Jul 23 '19 at 21:09

1 Answers1

0

Standard output streams provide a tellp() method which can be used to determine the current write position. The type and meaning of the return value is implementation-defined, but for it to be useful, it must return distinct values.

#include <iostream>
#include <fstream>

int main()
{
    std::ofstream out{"/tmp/test"};
    auto const empty_pos = out.tellp();

    std::clog.setf(std::ios_base::boolalpha);

    std::clog << "At start: " << (out.tellp() != empty_pos) << '\n';
    out << 'c';
    std::clog << "After writing 1 char: " << (out.tellp() != empty_pos) << '\n';
}

In principle, empty_pos may be different for each stream, so a truly portable program will take that into account.

Note also that this doesn't necessarily mean that the output is visible to other programs - use std::flush if that's important.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103