【Erlang新手成长日记】文件读写

参考文档:

  《Programming Erlang》,第13章:Programming with Files

  官方文档,file模块io模块 filename模块

示例:

%% 文件读写示例
-module(file_example).

-export([write/2, read/1]).

%% --------------------
%% 写入文件
%% write(Content, FileName) -> {ok, Content}
%% Content = string()
%% FileName = string()
%% --------------------
write(Content, FileName) when is_list(Content); is_list(FileName) ->
    FileAbsolutePath = lists:append([get_local_path(), "/", FileName]),
    {ok, IoDevice} = file:open(FileAbsolutePath, [append]),
    io:format(IoDevice, "~s", [Content]),
    file:close(IoDevice),
    {ok, Content}.

%% --------------------
%% 读取文件
%% read(FileName) -> binary()
%% FileName = string()
%% --------------------
read(FileName) when is_list(FileName) ->
    {ok, Content} = file:read_file(FileName),
    Content.

get_local_path() ->
    filename:dirname(code:which(?MODULE)).
posted on 2012-08-30 22:20  Anthony Li  阅读(1720)  评论(0编辑  收藏  举报

博客园博客已停止更新,博客地址:dyinigbleed.com