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

Recommended Answers

All 3 Replies

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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.