meds
meds

Reputation: 22926

Checking to see if ofstream is empty?

I've created an ofstream and there is a point in which I need to check if it's empty or has had things streamed into it.

Any ideas how I would go about doing this?

Upvotes: 1

Views: 5279

Answers (2)

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

The std::ofstream files don't support this directly. What you can do if this is an important requirement is to create a filtering stream buffer which internally used std::filebuf but also records if there was any output being done. This could look look as simple as this:

struct statusbuf:
    std::streambuf {
    statusbuf(std::streambuf* buf): buf_(buf), had_output_(false) {}
    bool had_output() const { return this->had_output_; }
private:
     int overflow(int c) {
         if (!traits_type::eq_int_type(c, traits_type::eof())) {
             this->had_output_ = true;
         }
         return this->buf_->overflow(c);
     }
     std::streambuf* buf_;
     bool            had_output_;
};

You can initialize an std::ostream with this and query the stream buffer as needed:

std::ofstream out("some file");
statusbuf     buf(out.rdbuf());
std::ostream  sout(&buf);

std::cout << "had_output: " << buf.had_output() << "\n";
sout << "Hello, world!\n";
std::cout << "had_ouptut: " << buf.had_output() << "\n";

Upvotes: 2

WeaselFox
WeaselFox

Reputation: 7380

you could use ofstream.rdbuff to get the file buffer and than use streambuf::sgetn to read it. I believe that should work.

Upvotes: 1

Related Questions