Erlang Central

Save Data to a File

Revision as of 12:23, 20 September 2006 by Dmitriid (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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)