【问题标题】:How to read single line from file in Erlang如何在 Erlang 中从文件中读取单行
【发布时间】:2014-10-13 12:25:35
【问题描述】:

我是 Erlang 和 stackoverflow 的新手。我一直在搜索有关如何使用 Erlang 从 .txt 文件中读取字符串的线程。我还想使用string:tokens 将其分成单词,有人告诉我可以使用 io:get_line 来完成此操作,但我一定做错了什么。这是我写的代码。任何指导将不胜感激!

-module(lab6).
-export([file/1]).

file(fName) ->
file:open(fName, [read]),
string:tokens(io:get_line(fName), ". ").

【问题讨论】:

    标签: string file erlang


    【解决方案1】:
    -module(lab6).
    -export([file/1]).
    
    file(FName) ->  % a variable must start by an Upper case character, otherwise it is an atom
        {ok,IoDevice} = file:open(FName, [read]), % file:open/2 returns the tuple {ok,IoDevice} if it succeeds.
                                                  % IoDevice is the file descriptor you will use for further accesses
        string:tokens(io:get_line(IoDevice,""), ". "). % you must use the file descriptor to read a new line, get_line
                                                   % is expecting 2 arguments, the second one is a prompt, not used here
                                                   % this code will split the first line of the file FName using
                                                   % the dot and the white space as separators. It will then returns
                                                   % the results letting the file open, but with the file descriptor
                                                   % lost! so no chance to continue to read the lines like this.
    

    你可以看看Learn you some erlang,这是一个学习Erlang的好网站。

    【讨论】:

    • 非常感谢帕斯卡!我不敢相信我忘记了大写!这一直是我错误的主要来源。多么令人沮丧!
    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    相关资源
    最近更新 更多