Fsharp-basic-io

提供:Dev Guides
移動先:案内検索

F#-基本的なI/O

基本入出力には以下が含まれます-

  • コンソールからの読み取りとコンソールへの書き込み。
  • ファイルの読み取りと書き込み。

Core.Printfモジュール

コンソールへの書き込みには、_printf_および_printfn_関数を使用しました。 このセクションでは、F#の Printf モジュールの詳細を調べます。

上記の関数とは別に、F#の_Core.Printf_モジュールには、%マーカーをプレースホルダーとして使用して印刷および書式設定するためのさまざまなメソッドがあります。 次の表は、簡単な説明とメソッドを示しています-

Value Description
bprintf : StringBuilder → BuilderFormat<'T> → 'T Prints to a StringBuilder.
eprintf : TextWriterFormat<'T> → 'T Prints formatted output to stderr.
eprintfn : TextWriterFormat<'T> → 'T Prints formatted output to stderr, adding a newline.
failwithf : StringFormat<'T,'Result> → 'T Prints to a string buffer and raises an exception with the given result.
fprintf : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer.
fprintfn : TextWriter → TextWriterFormat<'T> → 'T Prints to a text writer, adding a newline.
kbprintf : (unit → 'Result) → StringBuilder → BuilderFormat<'T,'Result> → 'T Like bprintf, but calls the specified function to generate the result.
kfprintf : (unit → 'Result) → TextWriter → TextWriterFormat<'T,'Result> → 'T Like fprintf, but calls the specified function to generate the result.
kprintf : (string → 'Result) → StringFormat<'T,'Result> → 'T Like printf, but calls the specified function to generate the result. For example, these let the printing force a flush after all output has been entered onto the channel, but not before.
ksprintf : (string → 'Result) → StringFormat<'T,'Result> → 'T Like sprintf, but calls the specified function to generate the result.
printf : TextWriterFormat<'T> → 'T Prints formatted output to stdout.
printfn : TextWriterFormat<'T> → 'T Prints formatted output to stdout, adding a newline.
sprintf : StringFormat<'T> → 'T Prints to a string by using an internal string buffer and returns the result as a string.

フォーマット仕様

フォーマット仕様は、プログラマーのニーズに応じて、入力または出力のフォーマットに使用されます。

これらは、フォーマットプレースホルダーを示す%マーカー付きの文字列です。

Formatプレースホルダーの構文は次のとおりです-

%[flags][width][.precision][type]
*type* は次のように解釈されます-
Type Description
%b Formats a bool, *formatted as true or false*.
%c Formats a character.
%s Formats a *string, *formatted as its contents, without interpreting any escape characters.
%d, %i Formats any basic integer type formatted as a decimal integer, signed if the basic integer type is signed.
%u Formats any basic integer type formatted as an unsigned decimal integer.
%x Formats any basic integer type formatted as an unsigned hexadecimal integer, using lowercase letters a through f.
%X Formats any basic integer type formatted as an unsigned hexadecimal integer, using uppercase letters A through F.
%o Formats any basic integer type formatted as an unsigned octal integer.
%e, %E, %f, %F, %g, %G Formats any basic floating point type* (float, float32) *formatted using a C-style floating point format specifications.
%e, %E Formats a 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 Formats a 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 Formats a signed value printed in f or e format, whichever is more compact for the given value and precision.
%M Formats a Decimal value.
%O Formats any value, printed by boxing the object and using its* ToString *method.
%A, %+A Formats any value, printed with the default layout settings. Use %+A to print the structure of discriminated unions with internal and private representations.
%a

A general format specifier, requires two arguments. The first argument is a function which accepts two arguments: first, a context parameter of the appropriate type for the given formatting function (for example, a TextWriter), and second, a value to print and which either outputs or returns appropriate text.

2番目の引数は、印刷する特定の値です。

%t A general format specifier, requires one argument: a function which accepts a context parameter of the appropriate type for the given formatting function (aTextWriter) and which either outputs or returns appropriate text. Basic integer types are* byte, sbyte, int16, uint16, int32, uint32, int64, uint64, nativeint, and unativeint. Basic floating point types are float and float32.*
*width* はオプションのパラメーターです。 結果の最小幅を示す整数です。 たとえば、%5dは、少なくとも5文字のスペースを含む整数を出力します。

有効な*フラグ*は次の表に記載されています-

Value Description
0 Specifies to add zeros instead of spaces to make up the required width.
- Specifies to left-justify the result within the width specified.
+ Specifies to add a + character if the number is positive (to match a - sign for negative numbers).
' ' (space) Specifies to add an extra space if the number is positive (to match a - sign for negative numbers).
# Invalid.

printf "Hello "
printf "World"
printfn ""
printfn "Hello "
printfn "World"
printf "Hi, I'm %s and I'm a %s" "Rohit" "Medical Student"

printfn "d: %f" 212.098f
printfn "e: %f" 504.768f

printfn "x: %g" 212.098f
printfn "y: %g" 504.768f

printfn "x: %e" 212.098f
printfn "y: %e" 504.768f
printfn "True: %b" true

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Hello World
Hello
World
Hi, I'm Rohit and I'm a Medical Studentd: 212.098000
e: 504.768000
x: 212.098
y: 504.768
x: 2.120980e+002
y: 5.047680e+002
True: true

コンソールクラス

このクラスは、.NETフレームワークの一部です。 コンソールアプリケーションの標準入力、出力、およびエラーストリームを表します。

コンソールから読み取り、コンソールに書き込むためのさまざまな方法を提供します。 次の表は、メソッドを示しています-

Method Description
Beep() Plays the sound of a beep through the console speaker.
Beep(Int32, Int32) Plays the sound of a beep of a specified frequency and duration through the console speaker.
Clear Clears the console buffer and corresponding console window of display information.
MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32) Copies a specified source area of the screen buffer to a specified destination area.
MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor) Copies a specified source area of the screen buffer to a specified destination area.
OpenStandardError() Acquires the standard error stream.
OpenStandardError(Int32) Acquires the standard error stream, which is set to a specified buffer size.
OpenStandardInput() Acquires the standard input stream.
OpenStandardInput(Int32) Acquires the standard input stream, which is set to a specified buffer size.
OpenStandardOutput() Acquires the standard output stream.
OpenStandardOutput(Int32) Acquires the standard output stream, which is set to a specified buffer size.
Read Reads the next character from the standard input stream.
ReadKey() Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window.
ReadKey(Boolean) Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window.
ReadLine Reads the next line of characters from the standard input stream.
ResetColor Sets the foreground and background console colors to their defaults.
SetBufferSize Sets the height and width of the screen buffer area to the specified values.
SetCursorPosition Sets the position of the cursor.
SetError Sets the Error property to the specified TextWriter object.
SetIn Sets the In property to the specified TextReader object.
SetOut Sets the Out property to the specified TextWriter object.
SetWindowPosition Sets the position of the console window relative to the screen buffer.
SetWindowSize Sets the height and width of the console window to the specified values.
Write(Boolean) Writes the text representation of the specified Boolean value to the standard output stream.
Write(Char) Writes the specified Unicode character value to the standard output stream.
Write(Char[]) Writes the specified array of Unicode characters to the standard output stream.
Write(Decimal) Writes the text representation of the specified Decimal value to the standard output stream.
Write(Double) Writes the text representation of the specified double-precision floating-point value to the standard output stream.
Write(Int32) Writes the text representation of the specified 32-bit signed integer value to the standard output stream.
Write(Int64) Writes the text representation of the specified 64-bit signed integer value to the standard output stream.
Write(Object) Writes the text representation of the specified object to the standard output stream.
Write(Single) Writes the text representation of the specified single-precision floating-point value to the standard output stream.
Write(String) Writes the specified string value to the standard output stream.
Write(UInt32) Writes the text representation of the specified 32-bit unsigned integer value to the standard output stream.
Write(UInt64) Writes the text representation of the specified 64-bit unsigned integer value to the standard output stream.
Write(String, Object) Writes the text representation of the specified object to the standard output stream using the specified format information.
Write(String, Object[]) Writes the text representation of the specified array of objects to the standard output stream using the specified format information.
Write(Char[], Int32, Int32) Writes the specified subarray of Unicode characters to the standard output stream.
Write(String, Object, Object) Writes the text representation of the specified objects to the standard output stream using the specified format information.
Write(String, Object, Object, Object) Writes the text representation of the specified objects to the standard output stream using the specified format information.
Write(String, Object, Object, Object, Object) Writes the text representation of the specified objects and variable-length parameter list to the standard output stream using the specified format information.
WriteLine() Writes the current line terminator to the standard output stream.
WriteLine(Boolean) Writes the text representation of the specified Boolean value, followed by the current line terminator, to the standard output stream.
WriteLine(Char) Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream.
WriteLine(Char[]) Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream.
WriteLine(Decimal) Writes the text representation of the specified Decimal value, followed by the current line terminator, to the standard output stream.
WriteLine(Double) Writes the text representation of the specified double-precision floating-point value, followed by the current line terminator, to the standard output stream.
WriteLine(Int32) Writes the text representation of the specified 32-bit signed integer value, followed by the current line terminator, to the standard output stream.
WriteLine(Int64) Writes the text representation of the specified 64-bit signed integer value, followed by the current line terminator, to the standard output stream.
WriteLine(Object) Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream.
WriteLine(Single) Writes the text representation of the specified single-precision floating-point value, followed by the current line terminator, to the standard output stream.
WriteLine(String) Writes the specified string value, followed by the current line terminator, to the standard output stream.
WriteLine(UInt32) Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream.
WriteLine(UInt64) Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line terminator, to the standard output stream.
WriteLine(String, Object) Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
WriteLine(String, Object[]) Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information.
WriteLine(Char[], Int32, Int32) Writes the specified subarray of Unicode characters, followed by the current line terminator, to the standard output stream.
WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
WriteLine(String, Object, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
WriteLine(String, Object, Object, Object, Object) Writes the text representation of the specified objects and variable-length parameter list, followed by the current line terminator, to the standard output stream using the specified format information.

次の例は、コンソールからの読み取りとコンソールへの書き込みを示しています-

open System
let main() =
   Console.Write("What's your name? ")
   let name = Console.ReadLine()
   Console.Write("Hello, {0}\n", name)
   Console.WriteLine(System.String.Format("Big Greetings from {0} and {1}", "finddevguides", "Absoulte Classes"))
   Console.WriteLine(System.String.Format("|{0:yyyy-MMM-dd}|", System.DateTime.Now))
main()

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

What's your name? Kabir
Hello, Kabir
Big Greetings from finddevguides and Absoulte Classes
|2015-Jan-05|

System.IO名前空間

System.IO名前空間には、基本的なI/Oを実行するためのさまざまな便利なクラスが含まれています。

これには、ファイルとデータストリームの読み取りと書き込みを可能にするタイプまたはクラス、および基本的なファイルとディレクトリのサポートを提供するタイプが含まれています。

ファイルシステムでの作業に役立つクラス-

  • System.IO.Fileクラスは、ファイルの作成、追加、削除に使用されます。
  • System.IO.Directoryクラスは、ディレクトリの作成、移動、および削除に使用されます。
  • System.IO.Pathクラスは、ファイルパスを表す文字列に対して操作を実行します。
  • System.IO.FileSystemWatcherクラスを使用すると、ユーザーはディレクトリの変更をリッスンできます。

ストリームの操作に役立つクラス(バイトのシーケンス)-

  • System.IO.StreamReaderクラスは、ストリームから文字を読み取るために使用されます。
  • System.IO.StreamWriterクラスは、ストリームに文字を書き込むために使用されます。
  • System.IO.MemoryStreamクラスは、メモリ内のバイトストリームを作成します。

次の表は、簡単な説明と名前空間で提供されるすべてのクラスを示しています-

Class Description
BinaryReader Reads primitive data types as binary values in a specific encoding.
BinaryWriter Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
BufferedStream Adds a buffering layer to read and write operations on another stream.
Directory Exposes static methods for creating, moving, and enumerating through directories and subdirectories.
DirectoryInfo Exposes instance methods for creating, moving, and enumerating through directories and subdirectories.
DirectoryNotFoundException The exception that is thrown when part of a file or directory cannot be found.
DriveInfo Provides access to information on a drive.
DriveNotFoundException The exception that is thrown when trying to access a drive or share that is not available.
EndOfStreamException The exception that is thrown when reading is attempted past the end of a stream.
ErrorEventArgs Provides data for the FileSystemWatcher.Error event.
File Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.
FileFormatException The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed.
FileInfo Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
FileLoadException The exception that is thrown when a managed assembly is found but cannot be loaded.
FileNotFoundException The exception that is thrown when an attempt to access a file that does not exist on disk fails.
FileStream Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.
FileSystemEventArgs Provides data for the directory events − Changed, Created, Deleted.
FileSystemInfo Provides the base class for both FileInfo and DirectoryInfo objects.
FileSystemWatcher Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.
InternalBufferOverflowException The exception thrown when the internal buffer overflows.
InvalidDataException The exception that is thrown when a data stream is in an invalid format.
IODescriptionAttribute Sets the description visual designers can display when referencing an event, extender, or property.
IOException The exception that is thrown when an I/O error occurs.
MemoryStream Creates a stream whose backing store is memory.
Path Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
PathTooLongException The exception that is thrown when a path or file name is longer than the system-defined maximum length.
PipeException Thrown when an error occurs within a named pipe.
RenamedEventArgs Provides data for the Renamed event.
Stream Provides a generic view of a sequence of bytes. This is an abstract class.
StreamReader Implements a TextReader that reads characters from a byte stream in a particular encoding.
StreamWriter Implements a TextWriter for writing characters to a stream in a particular encoding. To browse the .NET Framework source code for this type, see the Reference Source.
StringReader Implements a TextReader that reads from a string.
StringWriter Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.
TextReader Represents a reader that can read a sequential series of characters.
TextWriter Represents a writer that can write a sequential series of characters. This class is abstract.
UnmanagedMemoryAccessor Provides random access to unmanaged blocks of memory from managed code.
UnmanagedMemoryStream Provides access to unmanaged blocks of memory from managed code.
WindowsRuntimeStorageExtensions Contains extension methods for the IStorageFile and IStorageFolder interfaces in the Windows Runtime when developing Windows Store apps.
WindowsRuntimeStreamExtensions Contains extension methods for converting between streams in the Windows Runtime and managed streams in the .NET for Windows Store apps.

次の例では、test.txtというファイルを作成し、そこにメッセージを書き込み、ファイルからテキストを読み取り、コンソールに印刷します。

-これを行うために必要なコードの量は驚くほど少ないです!

open System.IO//Name spaces can be opened just as modules
File.WriteAllText("test.txt", "Hello There\n Welcome to:\n Tutorials Point")
let msg = File.ReadAllText("test.txt")
printfn "%s" msg

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Hello There
Welcome to:
Tutorials Point