Ways to Read a File

Let’s look at some options when it comes to reading files. We’ll start by writing five little programs that open a file and input the data in a number of ways.

The contents of a file are just a sequence of bytes. Whether they mean anything depends upon the interpretation of these bytes.

To demonstrate this, we’ll use the same input file for all our examples. It actually contains a sequence of Erlang terms. Depending upon how we open and read the file, we can interpret the contents as a sequence of Erlang terms, as a sequence of text lines, or as raw chunks of binary data with no particular interpretation.

Here’s the raw data in the file:

data1.dat
 
{person, "joe", "armstrong",
 
[{occupation, programmer},
 
{favoriteLanguage, ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.