Back

elixir - 11. IO, file, Path, StringIO

发布时间: 2019-03-04 06:26:00

参考: https://elixir-lang.org/getting-started/io-and-the-file-system.html

IO的基本用法

iex(14)> IO.puts "hihihi"
hihihi
:ok
iex(15)> IO.gets "hi, input a key?"
hi, input a key?3
"3\n"
iex(16)> IO.puts :stderr, "failed"
failed
:ok

File module

iex(17)> {:ok, file} = File.open("hello", [:write])
{:ok, #PID<0.127.0>}
iex(18)> IO.binwrite file, "world"
:ok
iex(21)> File.close(file)
:ok
iex(22)> File.read("hello")
{:ok, "world"}

加上叹号!会让返回值更加精简:

iex(22)> File.read("hello")
{:ok, "world"}
iex(23)> File.read!("hello")
"world"

Path

iex(24)> Path.join "opt", "app"
"opt/app"
iex(25)> Path.join "/opt", "app"
"/opt/app"
iex(26)> Path.expand("~/hi")    # 可以把 ~  变成 真实路径 
"/home/siwei/hi"

StringIO

iex(27)> {:ok, pid} = StringIO.open "hello"
{:ok, #PID<0.138.0>}
iex(28)> IO.read pid, 2
"he"

GroupLeader 跟stdio

iex(29)> IO.puts :stdio, "hello"
hello
:ok
iex(30)> IO.puts Process.group_leader(), "hello"
hello
:ok

Back