Erlang Central

Difference between revisions of "Save Data to a File"

From ErlangCentral Wiki

(Page created. Content added)
 
m (Linked functions)
Line 34:Line 34:
 
</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.
+
We attempt to open the file. The [http://www.erlang.se/doc/doc-5.5/lib/kernel-2.11/doc/html/file.html#open/2 file:open/2] function returns either {ok, IODevice} on success or {error, Reason} on failure. So, we check for both conditions.
  
 
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):
 
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):
Line 41:Line 41:
 
</code>
 
</code>
  
We further check for return codes from the io:fwrite/3 function and never forget to close the file:
+
We further check for return codes from the [http://www.erlang.se/doc/doc-5.5/lib/stdlib-1.14/doc/html/io.html#fwrite/3 io:fwrite/3] function and never forget to close the file:
 
<code>
 
<code>
 
file:close(IoDevice)
 
file:close(IoDevice)

Revision as of 12:26, 20 September 2006

Problem

You want to save some data to a file.

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.

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:

case file:open(PathToFile, [read, write]) of 

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.

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):

case io:fwrite(IoDevice, "~s", [Data]) of

We further check for return codes from the io:fwrite/3 function and never forget to close the file:

file:close(IoDevice)