I am trying to writing into the file and reading the content from the file, I able to write into the file but I unable to read the contents from the file.
Tried Code:
-module(main).
-export([file_wr/1,file_wrt/2,file_rede/2]).
file_wr(Str) ->
{ok,File} = file:open("input.txt",[write]),
D = [[D] || D <- Str],
file_wrt(File,D),
file_rede(File,D),
file:closeall().
file_wrt(File,[]) ->
File;
file_wrt(File,[First | Last]) ->
io:fwrite(File, "~s",[First]),
file_wrt(File,Last).
file_rede(File,[]) ->
file:close(File),
io:fwrite("\nCompleted\n");
file_rede(File,D) ->
{ok,List} = file:open(File,[read]),
{ok,Read} = file:read(List,1024*1024),
case io:read(Read,"") of
eof ->
file:close(File), D;
Item ->
file_rede(File,D ++ [Item])
end.
And I modified the above code to the below mentioned that will writing/reading the contents into/from the file. To achieve this, I written the two modules (), the reading module is imported into the written module in the below code.
Code for Reading the Contents from the file:
-module(file_reading).
-export([reading/1,readlines/1,get_all_lines/2]).
reading(FileName) ->
Lines =readlines(FileName),
io:format("~s~n",[Lines]).
readlines(FileName) ->
{ok, Device} = file:open(FileName, [read]),
get_all_lines(Device, []).
get_all_lines(Device, Accum) ->
case io:get_line(Device, " ") of
eof -> file:close(Device), Accum;
Line -> get_all_lines(Device, Accum ++ [Line])
end.
The above module is import into the writing module , it will be executing in single module for both writing and reading from the single file.
Code for Writing and reading the contents from the file:
**
-module(file_writing).
-export([start/1,file_wrt/2]).
-import(file_reading,[reading/1]). #Importing the reading from the file_reading module and I defined in the same main branch.
start(FileName) ->
io:format("~nReading the contents to the given file line by line: ~s ~n",[FileName]),
String = io:get_line("Enter a string: "),
L = [[L] || L <- String ],
file_wrt(FileName,L),
file:close(FileName),
io:format("~nPrinting the contents of the given file: ~s ~n ",[FileName]),
file_reading:reading(FileName).
file_wrt(FileName,L) ->
{ok, S} = file:open(FileName, [write,append]),
lists:foreach(fun(X) -> io:fwrite(S, "~s",[X]) end, L),
file:close(S).
**
1条答案
按热度按时间gpnt7bae1#
您的程式码会失败,因为您将数据传递到预期的I/O装置。
1.在
file_rede/2
函数中,首先调用file:open/2
,如果成功,则返回{ok, IoDevice}
。IoDevice
变量类似于文件描述符或文件句柄。在代码中,I/O设备变量命名为List
。1.然后将
List
作为第一个参数正确地传递给file:read/2
,file:read/2
成功返回{ok, Data}
,其中Data
是从文件中读取的数据。在代码中,数据变量名为Read
。1.但是在下一步中,您调用
io:read/2
,将Read
作为第一个参数传递,其中io:read/2
期望将I/O设备作为第一个参数。注意,
io:read/2
从它的I/O设备参数中读取Erlang术语,首先将它的第二个参数显示为提示符。