2015-10-27 82 views
1
-module(test). 
-export([run/1]). 

open_file(FileName, Mode) -> 
    {ok, Device} = file:open(FileName, [Mode, binary]), Device. 

close_file(Device) -> 
    ok = file:close(Device). 

read(File) -> 
    case file:read_line(File) of 
     {ok, Data} -> [Data | read(File)]; 
     eof  -> [] 
    end. 
run(InputFileName) -> 
    Device = open_file(InputFileName, read), 
    Data = read(Device), 
    [First |TheRest] = Data, 
    io:format("First line is ~p ~n", [First]), 
    close_file(Device). 

原始文件I/O使用Erlang,試圖讓輸入文件到列表

d1 and is program program the 
d2 a apply copyleft free free freedom 
d3 copyleft copyleft share share users 
d4 released software works 
d5 licenses licenses licenses licenses licenses software 
d8 apply 

莫名其妙地變成

50> test:run("input.txt"). 
First line is <<"d1\tand\tis\tprogram\tprogram\tthe\n">> 
ok 

這是代表一個列表的一種特殊的方式?還是我需要使用某種模塊將讀取轉換爲列表?

我的最終目標是使密鑰對的列表:

{d1 [and is program program the]} 

謝謝!

{ok, Device} = file:open(FileName, [Mode, binary]), Device. 

如果將其更改爲:

回答

1

當你打開文件,你從你的文件中讀取的數據被表示爲二進制,而不是字符串,因爲你指定binary模式:

{ok, Device} = file:open(FileName, [Mode]), Device. 

你的結果變成:

第一行是 「d1和程序是程序\ n」

爲了獲得最終的結果是,改變你的read/1功能如下:

read(File) -> 
    case file:read_line(File) of 
     {ok, Data} -> 
      [First|Rest] = string:tokens(Data, " \t\n"), 
      [{First,string:join(Rest, "\t")} | read(File)]; 
     eof -> [] 
    end. 

隨着這一變化,您的程序打印:

第一行是{ 「D1」,「和\ tis \ tprogram \ tprogram \ tthe「}

其中第二個元素是一個字符串,其中標記是標籤與原始數據分開。如果您希望第一個元素"d1"改爲原子d1(我無法確定您的問題是否符合您的要求),則可以使用list_to_atom/1進行轉換。

+0

嘿!我碰巧看過我的「Erlang編程」書的後面。 – 7stud