23

I was reading some project code and I found this,here MembersOfLibrary() is a constructor of class MenberOfLibrary

class MembersOfLibrary {
  public:
    MembersOfLibrary();
    ~MembersOfLibrary() {}
    void addMember();
    void removeMember();
    unsigned int searchMember(unsigned int MembershipNo);
    void searchMember(unsigned char * name);
    void displayMember();

  private:
    Members    libMembers;

};

MembersOfLibrary::MembersOfLibrary() {

    fstream memberData;
    memberData.open("member.txt", ios::in|ios::out);
    if(!memberData) {
    cout<<"\nNot able to create a file. MAJOR OS ERROR!! \n";
    }
    memberData.close();
}

What is ios::in|ios::out?

KidWithAComputer
  • 311
  • 1
  • 2
  • 10

3 Answers3

28
  • ios::in allows input (read operations) from a stream.
  • ios::out allows output (write operations) to a stream.
  • | (bitwise OR operator) is used to combine the two ios flags,
    meaning that passing ios::in | ios::out to the constructor
    of std::fstream enables both input and output for the stream.

Important things to note:

  • std::ifstream automatically has the ios::in flag set.
  • std::ofstream automatically has the ios::out flag set.
  • std::fstream has neither ios::in or ios::out automatically
    set. That's why they're explicitly set in your example code.
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Why do we need bitwise OR, just a logical OR operator cant be used here ? – KidWithAComputer Feb 05 '15 at 09:35
  • 4
    Logical and bitwise OR are two completely different things. A logical OR deals only with `bool` values. For example, it evaluates the second expression only if the first expression evaluated to `false`. – Emil Laine Feb 05 '15 at 09:40
  • 1
    Whereas a bitwise OR (which deals with integer values) goes through both values bit by bit and sets the bit in the resulting value if the bit was set in either of the two input values, thus resulting in a combining effect. – Emil Laine Feb 05 '15 at 09:43
  • good concise answer. Thanks. – netskink May 11 '22 at 12:50
5
 memberData.open("member.txt", ios::in|ios::out);

ios::in is used when you want to read from a file

ios::out is used when you want to write to a file

ios::in|ios::out means ios::in or ios::out, that is whichever is required is used

Here's a useful link

http://www.cplusplus.com/doc/tutorial/files/

Arun A S
  • 6,421
  • 4
  • 29
  • 43
5

ios::in and ios::out are openmode flags, and in your case combined with a binary or (|) operation. Thus the file is opened for reading and writing.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • On that cppreference.com reference page, where in the world does it tell us that `ios::` is the namespace `in` and `out` are in? – Gabriel Staples Oct 31 '20 at 21:11