Difference between the access modes of the `File` object (ie. w+, r+)

RubyFileFile IoIo

Ruby Problem Overview


When using files in Ruby, what is the difference between the r+ and w+ modes? What about the a+ mode?

Ruby Solutions


Solution 1 - Ruby

See http://www.tutorialspoint.com/ruby/ruby_input_output.htm

To quote: >r
Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode.

>r+
Read-write mode. The file pointer will be at the beginning of the file.

>w
Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

>w+
Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

>a
Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

>a+
Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

(empshasis mine.)

r+, w+, and a+ all do read-write. w+ truncates the file. a+ appends. w+ and a+ both create the file if it does not exist.)

Solution 2 - Ruby

For my own benefit / for reference purposes:

|mode|reads|writes|starts writing at|if preexists
|r   |yes  |      |n/a              |ok
|r+  |yes  |yes   |beginning        |fail
|w   |     |yes   |beginning        |overwrite
|w+  |yes  |yes   |beginning        |overwrite
|a   |     |yes   |end              |append
|a+  |yes  |yes   |end              |append

Solution 3 - Ruby

Access modes r+, w+ and a+ opens the file in read and write mode, but with the following difference:

r+ starts at beginning of file, but will not create a new file if it doesn't exists.

w+ truncates existing file to zero length if the file exists, otherwise creates a new file.

a+ starts at end of file if file exists, otherwise creates a new file.

Solution 4 - Ruby

Answer: Both r+ and w+ we can read ,write on file but r+ does not truncate (delete) the content of file as well it doesn’t create a new file if such file doesn’t exits while in w+ truncate the content of file as well as create a new file if such file doesn’t exists.

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
QuestionJust a learnerView Question on Stackoverflow
Solution 1 - RubyJonathan FinglandView Answer on Stackoverflow
Solution 2 - RubyPaul van LeeuwenView Answer on Stackoverflow
Solution 3 - Rubyuser1134160View Answer on Stackoverflow
Solution 4 - RubyrishiView Answer on Stackoverflow