0

Okay so I have fstreams that I swap between output and input. Is there anyway I can tell which openmode the fstream is in?

2
Contributors
3
Replies
19
Views
4 Years
Discussion Span
Last Post by deceptikon
0

Do you want the open mode that was passed to the constructor or open member function? Or do you want to know dynamically whether the last operation was a read or a write?

Ultimately, you'd need to maintain a flag providing this information, which could be stored in the fstream object using xalloc/iword/pword, if you so choose. Though a separate variable would be simpler, in my opinion. Just wrap it up in another class and call it good. For example to remember the open mode:

#include <fstream>
#include <ios>
#include <iostream>
#include <string>

using namespace std;

class File {
    ios::open_mode _mode;
    fstream _stream;
public:
    File(const string& filename, ios::openmode mode)
        : _mode(mode), _stream(filename.c_str(), mode)
    {}

    ios::openmode mode() const
    {
        return _mode;
    }

    fstream& get() {
        return _stream;
    }

    operator fstream&()
    {
        return get(); 
    }
};

int main()
{
    File fs("test.txt", ios::in);
    string s;

    while (getline(fs.get(), s)) {
        cout << s << '\n';
    }

    cout << "Opened in read mode: " << (fs.mode() & ios::in ? "YES" : "NO") << '\n';
    cout << "Opened in write mode: " << (fs.mode() & ios::out ? "YES" : "NO") << '\n';
}

Remembering the last operation is a little more tedious because it needs to be updated every time you perform a read or a write, but it's no more difficult.

Edited by deceptikon

0

I want to know dynamically whether the last operation was a read or a write. I would rather not make a class for this.

0

The solution is the same: you need to save that information somewhere on every read or write. If you don't want to use a separate variable or wrap everything up in a class, then look up the xalloc/iword/pword member functions provided by ios_base.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.