Skip to main content
ubuntuask.com

Back to all posts

How to Handle File I/O In Erlang?

Published on
5 min read
How to Handle File I/O In Erlang? image

Best Books for Learning File I/O in Erlang to Buy in October 2025

1 Programming Erlang: Software for a Concurrent World (Pragmatic Programmers)

Programming Erlang: Software for a Concurrent World (Pragmatic Programmers)

BUY & SAVE
$27.34 $42.00
Save 35%
Programming Erlang: Software for a Concurrent World (Pragmatic Programmers)
2 Erlang Programming: A Concurrent Approach to Software Development

Erlang Programming: A Concurrent Approach to Software Development

BUY & SAVE
$39.99
Erlang Programming: A Concurrent Approach to Software Development
3 The BEAM Book: Understanding the Erlang Runtime System

The BEAM Book: Understanding the Erlang Runtime System

BUY & SAVE
$25.00
The BEAM Book: Understanding the Erlang Runtime System
4 Learn You Some Erlang for Great Good!: A Beginner's Guide

Learn You Some Erlang for Great Good!: A Beginner's Guide

  • QUALITY ASSURED: GENTLY USED BOOKS IN GREAT CONDITION.
  • ECO-FRIENDLY CHOICE: SAVE TREES BY BUYING USED INSTEAD OF NEW.
  • AFFORDABLE PRICES: GET YOUR FAVORITE TITLES AT UNBEATABLE PRICES!
BUY & SAVE
$59.99
Learn You Some Erlang for Great Good!: A Beginner's Guide
5 Designing for Scalability with Erlang/OTP: Implement Robust, Fault-Tolerant Systems

Designing for Scalability with Erlang/OTP: Implement Robust, Fault-Tolerant Systems

BUY & SAVE
$40.08 $49.99
Save 20%
Designing for Scalability with Erlang/OTP: Implement Robust, Fault-Tolerant Systems
6 Programming Erlang: Software for a Concurrent World

Programming Erlang: Software for a Concurrent World

BUY & SAVE
$31.50 $36.95
Save 15%
Programming Erlang: Software for a Concurrent World
+
ONE MORE?

In Erlang, file input/output (I/O) operations are handled using built-in functions and modules that provide convenient and efficient ways to read from and write to files. Here's an overview of how to handle file I/O in Erlang:

Reading from a File:

  1. To read from a file, first, open the file using the file:open/2 function. This function takes two arguments: the file name and the read mode.
  2. Once the file is open, you can use various functions to read data from it. The most commonly used function is file:read/2, which reads a specified number of bytes from the file.
  3. After reading from the file, you can process the data as required.
  4. Continue reading from the file using file:read/2 until you've obtained all the necessary data.
  5. Finally, close the file using the file:close/1 function to release system resources.

Writing to a File:

  1. To write to a file, open the file using file:open/2, but this time specify the write mode.
  2. Once the file is open, you can use functions such as file:write/2 or file:write_binary/2 to write data to the file.
  3. Close the file using file:close/1 when you've finished writing to it.

Appending to a File:

  1. Similar to writing, open the file in append mode using file:open/2.
  2. Use functions like file:write/2 or file:write_binary/2 to append data to the file as needed.
  3. Close the file using file:close/1.

Other File Operations:

  1. Erlang also provides functions to navigate within the file, such as file:position/2 to set the file position, and file:where/1 to retrieve the current file position.
  2. You can additionally check the existence of a file with filelib:is_regular/1.
  3. Directories can be created using file:make_dir/1, and files or directories can be deleted using file:delete/1.

Note that Erlang also offers higher-level abstractions for file I/O, such as the io module that provides functions like io:format/2 for formatted printing to standard output or a file.

Remember to handle potential errors and exceptions that may occur during file I/O operations using error handling techniques like try/catch or error tuples.

How to write a CSV file in Erlang?

To write a CSV file in Erlang, you can use the file:write_file/2 function to write the content as a string to the file.

Here's an example of how you can write a list of lists representing CSV data to a file:

-module(csv_writer). -export([write_csv_file/2]).

write_csv_file(FilePath, Data) -> CsvContent = lists:flatten(format_csv_data(Data)), file:write_file(FilePath, CsvContent).

format_csv_data(Data) -> [RowStr ++ "\n" || Row <- Data, RowStr <- [format_csv_row(Row)]].

format_csv_row(Row) -> lists:concat([format_csv_value(Value) ++ "," || Value <- Row]).

format_csv_value(Value) -> case lists:member($", Value) of true -> Value =:= [$"| "|\s] orelse Value =:= [|\s $|], [$", Value, $"]; false -> Value end.

In this example, the write_csv_file/2 function takes in the file path FilePath and a list of lists Data, where each inner list represents a row in the CSV file.

The format_csv_data/1 function is used to format the CSV data into a flat list of strings, where each string represents a row in the CSV file. The format_csv_row/1 function is used to format each row by concatenating the CSV values with a comma separator. The format_csv_value/1 function is used to handle special cases, such as values containing a comma or quotes.

To use this module, you can call the write_csv_file/2 function with the file path and the data you want to write to the CSV file. For example:

csv_writer:write_csv_file("data.csv", [[1, 2, 3], ["foo", "bar", "baz"], ["hello", "world", "123"]]).

This will create a file named "data.csv" with the following content:

1,2,3 "foo","bar","baz" "hello","world","123"

Note that this example assumes that the file path is writable and that you have permissions to write to the specified location.

How to read a CSV file in Erlang?

To read a CSV file in Erlang, you can use the csv module from the stdlib library. Here's a step-by-step guide:

  1. First, make sure you have the stdlib library included in your project. You can include it by adding the following line to your Erlang module: -include_lib("stdlib/include/csv.hrl").
  2. Next, you need to open the CSV file for reading. You can do this using the file:open/2 function. Here's an example that opens a file named "data.csv": {ok, File} = file:open("data.csv", [read]).
  3. Once the file is open, you can use the csv:parse/1 function to read its contents. This function returns a list of lists, where each inner list represents a row in the CSV file. Here's an example that reads the CSV file contents: {ok, Data} = csv:parse(File).
  4. Finally, don't forget to close the file after reading its contents using the file:close/1 function: file:close(File).

That's it! You have now successfully read a CSV file in Erlang. You can now process the Data variable as needed.

How to write to a binary file in Erlang?

To write to a binary file in Erlang, you can make use of the file:write_file/2 function. Here's an example:

write_binary_file(Filename, Data) -> Mode = [write, binary], case file:open(Filename, Mode) of {ok, File} -> case file:write(File, Data) of ok -> file:close(File), io:format("Data written to ~s~n", [Filename]); {error, Reason} -> file:close(File), {error, Reason} end; {error, Reason} -> {error, Reason} end.

In the above example, the write_binary_file/2 function takes two arguments: Filename (the name of the file to write) and Data (the binary data to write to the file).

Here's an example usage:

BinaryData = <<1, 2, 3, 4>>, write_binary_file("output.bin", BinaryData).

In the above example, the binary data <<1, 2, 3, 4>> is written to the file named "output.bin" in binary format.

How to append to a file in Erlang?

To append to a file in Erlang, you can use the file:open/2, file:write/2, and file:close/1 functions. Here's an example:

append_to_file(Filename, Data) -> {ok, File} = file:open(Filename, [append]), io:fwrite(File, "~s~n", [Data]), file:close(File).

In this example, Filename is the name of the file you want to append to, and Data is the data you want to append.

Here's how you can use this function:

append_to_file("example.txt", "Hello, World!").

This will append the string "Hello, World!" to the file "example.txt".