Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 960
Just a learner Avatar asked Oct 17 '09 07:10

Just a learner


People also ask

What is the difference between R and W file mode?

r+: Opens a file in read and write mode. File pointer starts at the beginning of the file. w+: Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning.


2 Answers

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

like image 121
Jonathan Fingland Avatar answered Sep 17 '22 20:09

Jonathan Fingland


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 
like image 27
Paul van Leeuwen Avatar answered Sep 17 '22 20:09

Paul van Leeuwen