Save Data to a File

From Erlang Community

(Difference between revisions)
Revision as of 12:23, 20 September 2006 (edit)
Dmitriid (Talk | contribs)
(Page created. Content added)
← Previous diff
Current revision (14:22, 24 September 2006) (edit) (undo)
Ayrnieu (Talk | contribs)
(replace unnecessary reimplementation of file:write_file/2 with that function, and then add a tiny bit about saving consultable Erlang data structures, to make up for the blank page)
 
(One intermediate revision not shown.)
Line 5: Line 5:
== Solution == == Solution ==
-<code>+Where 'some data' is simply a list, you have this simple solution:
-save_to_file(PathToFile, Data) -> +
- case file:open(PathToFile, [read, write]) of +
- {ok, IoDevice} ->+
- case io:fwrite(IoDevice, "~s", [Data]) of+
- ok ->+
- file:close(IoDevice),+
- io:fwrite("File successfully written to ~s~n", [PathToFile]),+
- ok;+
- _ ->+
- file:close(IoDevice),+
- io:fwrite("File NOT written to ~s~n", [PathToFile]),+
- {error, "File not written"}+
- end;+
- {error, Reason} ->+
- {error, Reason} +
- end.+
-</code>+
- +
-This function accepts two arguments - path to the file we want the data to be written to (the file need not exist beforehand) and the data we wish to save.+
- +
-== Discussion ==+
- +
-Step by step the function does the following:+
<code> <code>
-case file:open(PathToFile, [read, write]) of +file:write_file(Path, Data).
</code> </code>
-We attempt to open the file. The file:open/2 function returns either {ok, IODevice} on success or {error, Reason} on failure. So, we check for both conditions.+But if you want to save an Erlang data structure, to perhaps file:consult/1 later, you have this slightly more complex solution:
- +
-In case of success we write data to the file (in this case we assume that data is actually a string, hence the "~s" switch):+
-<code>+
-case io:fwrite(IoDevice, "~s", [Data]) of+
-</code>+
-We further check for return codes from the io:fwrite/3 function and never forget to close the file: 
<code> <code>
-file:close(IoDevice)+file:write_file(Path,io_lib:fwrite("~p.\n",[Data])).
</code> </code>
[[Category:CookBook]][[Category:FileRecipes]] [[Category:CookBook]][[Category:FileRecipes]]

Current revision

[edit] Problem

You want to save some data to a file.

[edit] Solution

Where 'some data' is simply a list, you have this simple solution:

file:write_file(Path, Data).

But if you want to save an Erlang data structure, to perhaps file:consult/1 later, you have this slightly more complex solution:

file:write_file(Path,io_lib:fwrite("~p.\n",[Data])).
Erlang/OTP Projects
Personal tools