Stream Basics and File IO

   


Stream Basics and File I/O

In general, streams handle program input and program output. An input stream can be viewed as a sequence of bytes flowing into your program from a source device from which your program can read data. In contrast, an output stream can be regarded as a sequence of bytes to which your program can write that flows out from your program and are delivered to a destination device.

In C# and .NET, streams are represented by objects instantiated from stream classes located in the System.IO namespace.

You Have Already (Unknowingly) Used Streams

graphics/common.gif

By default, our familiar Console.ReadLine method reads from a standard input stream (an object of one of the System.IO stream classes) that brings characters written onscreen (with the keyboard) to your program. Similarly, the Console.WriteLine method writes, by default, to a standard output stream that sends characters to the screen.


The System.IO stream classes encapsulate and effectively shield you from underlying complexities related to hardware devices and the operating system. Not only does this make it much simpler to perform I/O operations, it provides a standard way to perform stream operations regardless of the destination devices involved. Furthermore, software maintenance becomes much easier; there is no need to change your C# programs just because an underlying technology has changed whether this be hardware or software related.

Text Files and Binary Files

Even though, technically speaking, all files consist of sequences of bits, any one file can either be regarded as being a text file or a binary file. A text file consists of a sequence of bits and bytes that contains a sequence of characters, when deciphered correctly. (Some text files are for example encoded using the Unicode standard.) We humans read text files. For example, the files you create, save, and open with the Notepad editor are text files. On the other hand, binary files are mostly generated and processed by computer programs.

C# programs provide output to and get input from binary files via binary streams. Similarly, text files are accessed and manipulated through character streams.

Binary files can be read from and written to a program efficiently because the data of a program are stored in the binary file exactly as it is stored in the computer memory; no processor hungry transformations are needed. This is not the case for the less efficient character streams. For example, all numeric data requires a processor-intensive process to be transformed into a text file.


   


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net