File opening mode in Ruby

Solution 1:

The file open modes are not really specific to ruby - they are part of IEEE Std 1003.1 (Single UNIX Specification). You can read more about it here:

http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

r or rb
    Open file for reading.

w or wb
    Truncate to zero length or create file for writing.

a or ab
    Append; open or create file for writing at end-of-file.

r+ or rb+ or r+b
    Open file for update (reading and writing).

w+ or wb+ or w+b
    Truncate to zero length or create file for update.

a+ or ab+ or a+b
    Append; open or create file for update, writing at end-of-file.

Any mode that contains the letter 'b' stands for binary file. If the 'b' is not present is a 'plain text' file.

The difference between 'open' and 'open for update' is indicated as:

When a file is opened with update mode ( '+' as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, the application shall ensure that output is not directly followed by input without an intervening call to fflush() or to a file positioning function ( fseek(), fsetpos(), or rewind()), and input is not directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.