File I/O Operations - Functional Programming

What are File I/O Operations?

Files are used to store the output of a program when the program closes. You can use various commands in different languages to access related information.
Here is a list of some operations that can be carried out on a file −
  • Creating a new file
  • Opening an existing file
  • Reading file contents
  • Searching data on a file
  • Writing into a new file
  • Updating contents to an existing file
  • Deleting a file
  • Closing a file

Writing into a File

You need to open the required file to write contents into a file. Incase if you doesn’t find a file, then a new file will be created.
Let’s see how to write contents into a file using C++.

Example

Note −
  • fstream is the stream class used to control file read/write operations.
  • ofstream is the stream class used to write contents into file.
Now observe that how to write contents into a file using Erlang, which is a functional programming language.
Note −
  • To open a file we have to use, open(filename,mode).
  • Syntax to write contents to file: write(filemode,file_content).
Output − When we run this code “Writing contents to file” will be written into the file Tempfile.txt. If the file has any existing content, then it will be overwritten.

Reading from a File

You need to open the specified file in reading mode to read from a file. Incase if the file doesn’t exist, then its respective method returns NULL.
Let’s see the below program that shows how to read the contents of a file in C++ −
It will produce the following output –
Below mentioned program describes how to perform the same operation using Erlang. You need to use the read_file(filename) method to read all the contents from the specified file.
It will produce the following output –

Delete an Existing File

Use file operation to delete an existing file. Let’s see the following program to delete an existing file using C++ −
It will produce the following output –
Below mentioned program describes how you can perform the same operation in Erlang. Here, we will use the method delete(filename) to delete an existing file.
Output − If the file “Tempfile.txt” exists, then it will be deleted.

Determining the Size of a File

Let’s see the below program to know the size of a file using C++. Here, the function fseek sets the position indicator associated with the stream to a new position, whereas ftell returns the current position in the stream.
Output − If the file “Tempfile.txt” exists, then it will show its size in bytes.
Below mentioned program display how you can perform the same operation in Erlang. Now,use the method file_size(filename) to know the size of the file.
Output − If the file “Tempfile.txt” exists, then it will show its size in bytes. Else, it will display “0”.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Functional Programming Topics