F# – Basic I/O

  • Post author:
  • Post category:F#
  • Post comments:1 Comment
F# - Basic I/O

F# Basic I/O (Input-Output) includes −

  • Reading from and writing into console.
  • Reading from and writing into file.

F# Basic I/O Core.Printf Module

We have used the printf and the printfn functions for writing into the console. In this section, we will look into the details of the Printf module of F#.

Apart from the above functions, the Core. Printf module of F# has various other methods for printing and formatting using % markers as placeholders. The following table shows the methods with brief description −

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

Format Specifications

Format specifications are used for formatting the input or output, according to the programmers’ need.

These are strings with % markers indicating format placeholders.

The syntax of Format placeholders is −

%[flags][width][.precision][type]

The type is interpreted as −

TypeDescription
%bFormats a bool, formatted as true or false.
%cFormats a character.
%sFormats a string, formatted as its contents, without interpreting any escape characters.
%d, %iFormats any basic integer type formatted as a decimal integer, signed if the basic integer type is signed.
%uFormats any basic integer type formatted as an unsigned decimal integer.
%xFormats any basic integer type formatted as an unsigned hexadecimal integer, using lowercase letters a through f.
%XFormats any basic integer type formatted as an unsigned hexadecimal integer, using uppercase letters A through F.
%oFormats any basic integer type formatted as an unsigned octal integer.
%e, %E, %f, %F, %g, %GFormat any basic floating-point type (float, float32) formatted using C-style floating-point format specifications.
%e, %EFormats 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 -.
%fFormats 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, %GFormats a signed value printed in f or e format, whichever is more compact for the given value and precision.
%MFormats a Decimal value.
%OFormats any value, printed by boxing the object and using its ToString method.
%A, %+AFormats any value, printed with the default layout settings. Use %+A to print the structure of discriminated unions with internal and private representations.
%aA general format specifier requires two arguments. The first argument is a function that 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. The second argument is the particular value to print.
%tA general format specifier requires one argument: a function that 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, native int, and nativist. Basic floating-point types are float and float32.

The width is an optional parameter. It is an integer that indicates the minimal width of the result. For example, %5d prints an integer with at least spaces of 5 characters.

Valid flags are described in the following table −

ValueDescription
0Specifies 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 extra space if the number is positive (to match a – sign for negative numbers).
#Invalid.

Example

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

When you compile and execute the program, it yields the following output −

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

The Console Class

This class is a part of the .NET framework. It represents the standard input, output, and error streams for console applications.

It provides various methods for reading from and writing into the console. The following table shows the methods −

MethodDescription
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.
ClearClears 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 specified buffer size.
OpenStandardInput()Acquires the standard input stream.
OpenStandardInput(Int32)Acquires the standard input stream, which is set to specified buffer size.
OpenStandardOutput()Acquires the standard output stream.
OpenStandardOutput(Int32)Acquires the standard output stream, which is set to specified buffer size.
ReadReads 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.
ReadLineReads the next line of characters from the standard input stream.
ResetColorSets the foreground and background console colors to their defaults.
SetBufferSizeSets the height and width of the screen buffer area to the specified values.
SetCursorPositionSets the position of the cursor.
SetErrorSets the Error property to the specified TextWriter object.
SetInSets the In property to the specified TextReader object.
SetOutSets the Out property to the specified TextWriter object.
SetWindowPositionSets the position of the console window relative to the screen buffer.
SetWindowSizeSets 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.

The following example demonstrates reading from console and writing into it −

Example

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}", "AdglobPoint", "Absoulte Classes"))
   Console.WriteLine(System.String.Format("|{0:yyyy-MMM-dd}|", System.DateTime.Now))
main()

When you compile and execute the program, it yields the following output −

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

The System.IO Namespace

The System.IO namespace contains a variety of useful classes for performing basic I/O.

It contains types or classes that allow reading and writing to files and data streams and types that provide basic file and directory support.

Classes useful for working with the file system −

  • The System.IO.File class is used for creating, appending, and deleting files.
  • System.IO.Directory class is used for creating, moving, and deleting directories.
  • System.IO.Path class performs operations on strings, which represent file paths.
  • System.IO.FileSystemWatcher class allows users to listen to a directory for changes.

Classes useful for working with the streams (sequence of bytes) −

  • System.IO.StreamReader class is used to read characters from a stream.
  • System.IO.StreamWriter class is used to write characters to a stream.
  • System.IO.MemoryStream class creates an in-memory stream of bytes.

The following table shows all the classes provided in the namespace along with a brief description −

ClassDescription
BinaryReaderReads primitive data types as binary values in a specific encoding.
BinaryWriterWrites primitive types in binary to a stream and supports writing strings in a specific encoding.
BufferedStreamAdds a buffering layer to read and write operations on another stream.
DirectoryExposes static methods for creating, moving, and enumerating through directories and subdirectories.
DirectoryInfoExposes instance methods for creating, moving, and enumerating through directories and subdirectories.
DirectoryNotFoundExceptionThe exception is thrown when part of a file or directory cannot be found.
DriveInfoProvides access to information on a drive.
DriveNotFoundExceptionThe exception is thrown when trying to access a drive or share that is not available.
EndOfStreamExceptionThe exception that is thrown when reading is attempted past the end of a stream.
ErrorEventArgsProvides data for the FileSystemWatcher.Error event.
FileProvides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.
FileFormatExceptionThe 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.
FileInfoProvides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
FileLoadExceptionThe exception is thrown when a managed assembly is found but cannot be loaded.
FileNotFoundExceptionThe exception that is thrown when an attempt to access a file that does not exist on disk fails.
FileStreamExposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.
FileSystemEventArgsProvides data for the directory events − Changed, Created, Deleted.
FileSystemInfoProvides the base class for both FileInfo and DirectoryInfo objects.
FileSystemWatcherListens to the file system change notifications and raises events when a directory, or file in a directory, changes.
InternalBufferOverflowExceptionThe exception is thrown when the internal buffer overflows.
InvalidDataExceptionThe exception is thrown when a data stream is in an invalid format.
IODescriptionAttributeSets the description visual designers can display when referencing an event, extender, or property.
IOExceptionThe exception is thrown when an I/O error occurs.
MemoryStreamCreates a stream whose backing store is memory.
PathPerforms operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
PathTooLongExceptionThe exception is thrown when a path or file name is longer than the system-defined maximum length.
PipeExceptionThrown when an error occurs within a named pipe.
RenamedEventArgsProvides data for the Renamed event.
StreamProvides a generic view of a sequence of bytes. This is an abstract class.
StreamReaderImplements a TextReader that reads characters from a byte stream in a particular encoding.
StreamWriterImplements 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.
StringReaderImplements a TextReader that reads from a string.
StringWriterImplements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.
TextReaderRepresents a reader that can read a sequential series of characters.
TextWriterRepresents a writer that can write a sequential series of characters. This class is abstract.
UnmanagedMemoryAccessorProvides random access to unmanaged blocks of memory from managed code.
UnmanagedMemoryStreamProvides access to unmanaged blocks of memory from managed code.
WindowsRuntimeStorageExtensionsContains extension methods for the IStorageFile and IStorageFolder interfaces in the Windows Runtime when developing Windows Store apps.
WindowsRuntimeStreamExtensionsContains extension methods for converting between streams in the Windows Runtime and managed streams in the .NET for Windows Store apps.

Example

The following example creates a file called test.txt, writes a message there, reads the text from the file, and prints it on the console.

Note − The amount of code needed to do this is surprisingly less!

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

When you compile and execute the program, it yields the following output −

Hello There
Welcome to:
Adglob Point

Next Topic – Click Here

This Post Has One Comment

Leave a Reply