Basics

Elixir IO

Input/Output in Elixir

Elixir IO module handles console output and file operations.

Introduction to Elixir IO Module

The Elixir IO module is a fundamental part of the Elixir language, providing a simple and efficient way to handle input and output operations. Whether you are working with the console or files, the IO module offers a suite of functions to manage these tasks effectively.

Console Output with IO.puts/1

The most commonly used function for displaying output in Elixir is IO.puts/1. It prints a string followed by a newline to the standard output, usually the console.

Reading Input with IO.gets/1

The IO.gets/1 function is used to read a line of input from the user. It takes a prompt string as an argument, which is displayed to the user before waiting for input.

Working with Files

Elixir's IO module also provides functions to work with files. The IO.read/2 and IO.write/2 functions allow you to read from and write to files, respectively.

Reading from a File

To read the contents of a file, you can use the IO.read/2 function. It requires the file path and the number of bytes to read, or :line for line-by-line reading.

Writing to a File

To write to a file, use the IO.write/2 function. You'll need to open the file in write mode.

Conclusion

The Elixir IO module is a versatile tool for managing input and output in both console and file contexts. By mastering functions such as IO.puts/1, IO.gets/1, IO.read/2, and IO.write/2, you can efficiently handle data in your Elixir applications.

Previous
Mix