F# 程式設計/輸入和輸出
| F# : 基本 I/O |
輸入和輸出,也稱為I/O,是指兩個硬體裝置之間或使用者和計算機之間進行的任何型別的通訊。這包括將文字列印到控制檯、讀寫磁碟檔案、透過套接字傳送資料、將資料傳送到印表機以及各種其他常見任務。
此頁面並非旨在全面介紹 .NET 的 I/O 方法(尋求全面參考的讀者鼓勵檢視 MSDN 上關於System.IO 名稱空間的優秀文件)。此頁面將簡要概述 F# 程式設計師可用於列印和處理檔案的一些基本方法。
到目前為止,您可能已經熟悉 Printf 模組 中的 printf、printfn、sprintf 及其變體。但是,為了更正式地描述這些方法,這些方法用於使用 % 標記作為佔位符的 printf 風格的列印和格式化
Print 方法接受一個格式字串和一系列引數,例如
> sprintf "Hi, I'm %s and I'm a %s" "Juliet" "Scorpio";;
val it : string = "Hi, I'm Juliet and I'm a Scorpio"
Printf 模組中的方法是型別安全的。例如,嘗試使用 int 佔位符替換字串會導致編譯錯誤
> sprintf "I'm %i years old" "kitty";;
sprintf "I'm %i years old" "kitty";;
---------------------------^^^^^^^^
stdin(17,28): error FS0001: The type 'string' is not compatible with any of the types
byte,int16,int32,int64,sbyte,uint16,uint32,uint64,nativeint,unativeint, arising from
the use of a printf-style format string.
根據 F# 文件,% 佔位符由以下部分組成
%[flags][width][.precision][type]
[flags](可選)
有效標誌為
- 0:新增零而不是空格以達到所需的寬度
- '-': 將結果在指定的寬度內左對齊
- '+': 如果數字為正,則新增 '+' 字元(以匹配負數的 '-' 符號)
- ' ': 如果數字為正,則新增一個額外的空格(以匹配負數的 '-' 符號)
[width](可選)
可選寬度是一個整數,表示結果的最小寬度。例如,%6d 列印一個整數,在它前面加空格以至少填充 6 個字元。如果寬度為 '*',則將使用一個額外的整數引數來指定相應的寬度。
- 任何數字
- '*':
[.precision](可選)
表示浮點數後的位數。
> sprintf "%.2f" 12345.67890;;
val it : string = "12345.68"
> sprintf "%.7f" 12345.67890;;
val it : string = "12345.6789000"
[type](必需)
以下佔位符型別將被解釋為以下內容
%b: bool, formatted as "true" or "false"
%s: string, formatted as its unescaped contents
%d, %i: any basic integer type formatted as a decimal integer, signed if the basic integer type is signed.
%u: any basic integer type formatted as an unsigned decimal integer
%x, %X, %o: any basic integer type formatted as an unsigned hexadecimal
(a-f)/Hexadecimal (A-F)/Octal integer
%e, %E, %f, %F, %g, %G:
any basic floating point type (float,float32) formatted
using a C-style floating point format specifications, i.e
%e, %E: Signed value having the form [-]d.dddde[sign]ddd where
d is a single decimal digit, dddd is one or more decimal
digits, ddd is exactly three decimal digits, and sign
is + or -
%f: Signed value having the form [-]dddd.dddd, where dddd is one
or more decimal digits. The number of digits before the
decimal point depends on the magnitude of the number, and
the number of digits after the decimal point depends on
the requested precision.
%g, %G: Signed value printed in f or e format, whichever is
more compact for the given value and precision.
%M: System.Decimal value
%O: Any value, printed by boxing the object and using it's ToString method(s)
%A: Any value, printed by using Microsoft.FSharp.Text.StructuredFormat.Display.any_to_string with the default layout settings
%a: A general format specifier, requires two arguments:
(1) a function which accepts two arguments:
(a) a context parameter of the appropriate type for the
given formatting function (e.g. an #System.IO.TextWriter)
(b) a value to print
and which either outputs or returns appropriate text.
(2) the particular value to print
%t: A general format specifier, requires one argument:
(1) a function which accepts a context parameter of the
appropriate type for the given formatting function (e.g.
an #System.IO.TextWriter)and which either outputs or returns
appropriate text.
Basic integer types are:
byte,sbyte,int16,uint16,int32,uint32,int64,uint64,nativeint,unativeint
Basic floating point types are:
float, float32
程式設計師可以使用 printf 方法列印到控制檯,但 F# 建議使用 System.Console.ReadLine() 方法讀取控制檯輸入。
.NET 包含它自己的格式說明符表示法。.NET 格式字串是無型別的。此外,.NET 的格式字串旨在可擴充套件,這意味著程式設計師可以實現自己的自定義格式字串。格式佔位符具有以下形式
{index[, length][:formatString]}
例如,在 fsi 中使用 String.Format 方法
> System.String.Format("Hi, my name is {0} and I'm a {1}", "Juliet", "Scorpio");;
val it : string = "Hi, my name is Juliet and I'm a Scorpio"
> System.String.Format("|{0,-50}|", "Left justified");;
val it : string = "|Left justified |"
> System.String.Format("|{0,50}|", "Right justified");;
val it : string = "| Right justified|"
> System.String.Format("|{0:yyyy-MMM-dd}|", System.DateTime.Now);;
val it : string = "|2009-Apr-06|"
有關 .NET 格式說明符的全面參考,請參閱數字格式字串、日期和時間格式字串以及列舉格式字串。
程式設計師可以使用 System.Console 類 讀取和寫入控制檯
open System
let main() =
Console.Write("What's your name? ")
let name = Console.ReadLine()
Console.Write("Hello, {0}", name)
main()
System.IO 名稱空間包含許多用於執行基本 I/O 的有用類。
以下類對於查詢主機檔案系統很有用
- System.IO.File 類公開了幾個用於建立、追加和刪除檔案的有用成員。
- System.IO.Directory 公開了用於建立、移動和刪除目錄的方法。
- System.IO.Path 對錶示檔案路徑的字串執行操作。
- System.IO.FileSystemWatcher 允許使用者監聽目錄以獲取更改。
流是位元組序列。.NET 提供了一些類,允許程式設計師使用流,包括
- System.IO.StreamReader 用於從流中讀取字元。
- System.IO.StreamWriter 用於將字元寫入流。
- System.IO.MemoryStream 建立記憶體中的位元組流。