File opening mode in Ruby

RubyFilePosix

Ruby Problem Overview


I am new programmar in Ruby. Can someone take an example about opening file with r+,w+,a+ mode in Ruby? What is difference between them and r,w,a?

Please explain, and provide an example.

Ruby Solutions


Solution 1 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionamir amirView Question on Stackoverflow
Solution 1 - RubymikuView Answer on Stackoverflow