Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File opening mode in Ruby

Tags:

file

posix

ruby

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.

like image 323
amir amir Avatar asked Aug 16 '11 22:08

amir amir


People also ask

When opening a file What does the mode a mean in Ruby?

Ruby students also learnAppend/Write only permission is denoted by 'a'. The main difference from the previous option is that the file pointer starts at the end of the file. This means the existing data in the file is not overwritten.

What does __ file __ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.

How do I write to a file in Ruby?

Writing text to a file with Ruby is reasonably straightforward. Just like many other languages, you need to open the file in "write" mode, write your data, and then close the file.


1 Answers

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.

like image 198
miku Avatar answered Sep 28 '22 16:09

miku