So, in the previous tutorial, we have created a file named myfirstfile.txt, with the below contents,
Now, let us see, how can we read the above file in Ruby.
We can use the read() Method to read the total file.
There are two modes for reading a file :
myfile = open("myfirstfile.txt", "r") str = myfile.read() puts str myfile.close()
myfile = open("myfirstfile.txt", "r")
str = myfile.read()
And initialised the contents of the file in a variable, str as a String.
puts str
myfile.close()
We can use the readline() Method to read the first line of the file.
myfile = open("myfirstfile.txt", "r") str = myfile.readline() puts str myfile.close()
So, in the above example, we have used the readline() Method to read the first line of the file.
str = myfile.readline()
Rest of the lines are just the same.
We can use the number of character with the read() Method to read the File by number of characters.
myfile = open("myfirstfile.txt", "r") str = myfile.read(9) puts str myfile.close()
So, in the above example, we have used the read() Method and specified 9 as argument to read the first 9 characters of the file.
str = myfile.read(9)
And got the below output.
In a huge
In the above example, we have used the read() Method and specified 9 as argument to read the first 9 characters of the file.
Now, the file pointer should be at 9.
And we can get the current file pointer using the tell() Method.
myfile = open("myfirstfile.txt", "r") str = myfile.read(9) puts myfile.tell() myfile.close()
And all we have done is used the tell() Method to get the position of the file pointer.
puts myfile.tell()
And as we know the current file pointer is at 9. So we got 9 as output.
In the above example, we have used the tell() Method to identify the current file pointer position.
Now, what if we want to change the file pointer, so that it points to some other location.
And we can achieve it using the seek() Method.
Let us see in the below example.
myfile = open("myfirstfile.txt", "r") str = myfile.read(9) puts myfile.tell() myfile.seek(0) puts myfile.tell() myfile.close()
So, if we see the output, we can see that the tell() Method is pointing to position 9.
puts myfile.tell()
Then we have used the seek() Method to reset the position of the pointer to 0.
myfile.seek(0)
And if you see the next tell() Method,
puts myfile.tell()
It points to location 0. As