我是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), ". ").
答案 0 :(得分: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的绝佳网站。