Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Streaming a file as a resource


In the Generating lazy (even infinite) sequences recipe, it was possible to understand the difference between eager and lazy evaluation, namely the use of Enum or Stream modules.

When working with files, it is possible to load all of the file's contents into the memory (File.read/1 or File.read!/1), or the file might be read a line or n bytes at a time (File.stream!/3). Using the File.stream! function allows you to work with really large files that might not fit the available memory.

In this recipe, we will read text from a file and output an uppercased version into a new file.

Getting ready

Start an IEx session and make sure you have stream_file.txt in a known location:

> iex

How to do it…

To read a file one line at a time (that is, streaming it), we will perform the following steps:

  1. First, let's get information about the file we will be loading:

    iex(1)> File.stat("<path_to_file>/stream_file.txt")
    %File.Stat{access: :read_write, atime: {{2014, 9, 20...