Ruby program to open a file in append mode, open if the file does not exist

Ruby Example: Write a program to open a file in append mode, open if the file does not exist.
Submitted by Nidhi, on February 12, 2022

Problem Solution:

In this program, we will open a file in append mode by specifying "a+" in the new() method, open if the file does not exist. Then we will write data into the end of the file.

Program/Source Code:

The source code to open a file in append mode, open if the file does not exist is given below. The given program is compiled and executed on Windows 10 Operating System successfully.

# Ruby program to open a file in append mode,
# open if the file does not exist.

# Open file in read-write mode.
fobj = File.new("NewFile.txt", "a+"); 

print "File opened in append mode.\n";

# Write data into file at the end
fobj.syswrite("Noida\n");

# Close file object
fobj.close();  

# Open file in read mode.
fobj = File.new("NewFile.txt", "r"); 

print "File opened in read mode.\n";

# Read data from file
puts fobj.read();

# Close file object
fobj.close();  

Output:

File opened in append mode.
File opened in read mode.
Noida

Explanation:

In the above program, we opened a file "NewFile.txt" in append mode ('a+') by creating object fobj of the File class. The 'a+' mode is used, if the file does not exist. Then we wrote data into the file. After that, we read the updated file and printed the result.

Ruby File Handling Programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.