檢視原始碼 StringIO (Elixir v1.16.2)

控制將字串包裝起來的 IO 裝置程序。

大部分 IO 模組中的函式,都可以將 StringIO IO 裝置傳遞為「裝置」。

範例

iex> {:ok, pid} = StringIO.open("foo")
iex> IO.read(pid, 2)
"fo"

摘要

函式

停止 IO 裝置,並傳回剩餘的輸入/輸出緩衝區。

傳回給定 IO 裝置目前的輸入/輸出緩衝區。

清除輸出緩衝區,並傳回其目前的內容。

建立 IO 裝置。

函式

@spec close(pid()) :: {:ok, {binary(), binary()}}

停止 IO 裝置,並傳回剩餘的輸入/輸出緩衝區。

範例

iex> {:ok, pid} = StringIO.open("in")
iex> IO.write(pid, "out")
iex> StringIO.close(pid)
{:ok, {"in", "out"}}
@spec contents(pid()) :: {binary(), binary()}

傳回給定 IO 裝置目前的輸入/輸出緩衝區。

範例

iex> {:ok, pid} = StringIO.open("in")
iex> IO.write(pid, "out")
iex> StringIO.contents(pid)
{"in", "out"}
@spec flush(pid()) :: binary()

清除輸出緩衝區,並傳回其目前的內容。

範例

iex> {:ok, pid} = StringIO.open("in")
iex> IO.write(pid, "out")
iex> StringIO.flush(pid)
"out"
iex> StringIO.contents(pid)
{"in", ""}
連結到此函式

open(string, options_or_function \\ [])

檢視原始碼
@spec open(
  binary(),
  keyword()
) :: {:ok, pid()}
@spec open(binary(), (pid() -> res)) :: {:ok, res} when res: var

建立 IO 裝置。

string 會是新建立裝置的初始輸入。

options_or_function 可以是選項的關鍵字清單,或是函式。

如果提供選項,結果會是 {:ok, pid},傳回已建立的 IO 裝置。選項 :capture_prompt 設定為 true 時,會將提示 (指定為 IO.get* 函式的引數) 納入裝置的輸出。

如果提供函數,裝置將會建立並傳送至函數。當函數傳回時,裝置將會關閉。最終結果將會是包含 :ok 和函數結果的元組。

範例

iex> {:ok, pid} = StringIO.open("foo")
iex> IO.gets(pid, ">")
"foo"
iex> StringIO.contents(pid)
{"", ""}

iex> {:ok, pid} = StringIO.open("foo", capture_prompt: true)
iex> IO.gets(pid, ">")
"foo"
iex> StringIO.contents(pid)
{"", ">"}

iex> StringIO.open("foo", fn pid ->
...>   input = IO.gets(pid, ">")
...>   IO.write(pid, "The input was #{input}")
...>   StringIO.contents(pid)
...> end)
{:ok, {"", "The input was foo"}}
連結到此函式

open(string, options, function)

檢視原始碼 (自 1.7.0 起)
@spec open(binary(), keyword(), (pid() -> res)) :: {:ok, res} when res: var

建立 IO 裝置。

string 會是新建立裝置的初始輸入。

裝置將會建立並傳送至所給的函數。當函數傳回時,裝置將會關閉。最終結果將會是包含 :ok 和函數結果的元組。

選項

  • :capture_prompt - 如果設為 true,提示 (指定為 IO.get* 函數的參數) 會擷取在輸出中。預設為 false

  • :encoding (自 v1.10.0 起) - IO 裝置的編碼。允許的值有 :unicode (預設) 和 :latin1

範例

iex> StringIO.open("foo", [], fn pid ->
...>   input = IO.gets(pid, ">")
...>   IO.write(pid, "The input was #{input}")
...>   StringIO.contents(pid)
...> end)
{:ok, {"", "The input was foo"}}

iex> StringIO.open("foo", [capture_prompt: true], fn pid ->
...>   input = IO.gets(pid, ">")
...>   IO.write(pid, "The input was #{input}")
...>   StringIO.contents(pid)
...> end)
{:ok, {"", ">The input was foo"}}