English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Using I / Erlang provides many methods when O is used. It has simpler classes that can provide the following functions for files-
Read file
Write to file
Check if a file is a file or a directory
Let's explore some file operations provided by Erlang. For these examples, we will assume that there is a file namedNewFile.txtcontaining the following text lines
Example1
Example2
Example3
In the following examples, this file will be used for read and write operations.
Perform routine operations on files using the methods available in the file library. To read a file, we need to use the open operation first, then use the read operation, which can be used as part of the file library. The syntax of these two methods is as follows.
Open file – Open(File,Mode)
Read file – read(FileHandler,NumberofBytes)
File −This is the location of the file to be opened.
Mode −This is the mode needed to open the file.
The following are some available modes-
Read −The file must be opened for reading.
Write−Open the file for writing. If it does not exist, it will be created. If the file exists and writing is not combined with reading, the file will be truncated.
Append−The file will be opened for writing, and if it does not exist, it will be created. All write operations on files opened with append will be performed at the end of the file.
Exclusive−When opening the file for writing, if the file does not exist, it will be created. If the file exists, open will return {error, exist}.
FileHandler−This is the file handle. This handle is returned when the file:open operation is used.
NumberofByte −This is the number of bytes of information that needs to be read from the file.
Open(File,Mode) −If the operation is successful, the file handle is returned.
read(FileHandler,NumberofBytes) −Return the read information requested from the file.
-module(helloworld). -export([start/). start() -> {ok, File} = file:open("Newfile.txt",[read]), Txt = file:read(File,1024 * 1024, io:fwrite("~p~n",[Txt]).
Output−When the above program is run, the following results will be obtained.
Example1
Now let's discuss some other methods that can be used for file operations-
Serial Number | Method and Description |
---|---|
1 | Can be used to read all the content of the file at once. |
2 | Used to write content to a file. |
3 | Used to copy an existing file. |
4 | This method is used to delete an existing file. |
5 | This method is used to list the contents of a specific directory. |
6 | This method is used to create a new directory. |
7 | This method is used to rename an existing file. |
8 | This method is used to determine the size of the file. |
9 | This method is used to determine whether the file is indeed a file. |
10 | This method is used to determine whether the directory is indeed a directory. |