Streams and files

19
C# 1 Streams and files CSC 298

description

CSC 298. Streams and files. Overview. Topics Streams – communicating with the outside world Data representation – bits and bytes Basic C# streams. Streams. C# model of communication: streams Sequence of data flowing from a source to a program, or from a program to a destination (sink) - PowerPoint PPT Presentation

Transcript of Streams and files

Page 1: Streams and files

C# 1

Streams and files

CSC 298

Page 2: Streams and files

C# 2

Overview

Topics Streams – communicating with the outside

world Data representation – bits and bytes Basic C# streams

Page 3: Streams and files

C# 3

Streams

C# model of communication: streams Sequence of data flowing from a source to a

program, or from a program to a destination (sink)

Huge variety of stream classes in System.IO Highly modular Some are data sources/sinks Others are wrapper classes that take data from a

stream and transform it somehow to produce a stream with different characteristics

Page 4: Streams and files

C# 4

Stream Processing

Basic idea the same for input & output

// input

open a stream

while more data

{

read & process next data

}

close stream

// output

open a stream

while more data

{

write data to stream

}

close stream

Page 5: Streams and files

C# 5

Opening & Closing Streams

Before a stream can be used it must be opened Create a stream object and connect it to source or

destination of the stream data Often done implicitly as part of creating stream

objects

When we’re done with a stream, it should be closed Cleans up any unfinished operations, then breaks

the connection between the program and the data source/destination

Page 6: Streams and files

C# 6

Data Representation

Underneath it’s all bits (binary digits – 0/1) Byte – group of 8 binary digits

Smallest addressable unit of memory

Meaning depends on interpretation 01000001 = int 65 = char ‘A’ 0011111 = int 63 = char ‘?’ 00111100 = int 54 = char ‘6’

But it’s still just bits

Page 7: Streams and files

C# 7

Some C# types (1) bool – 1 byte (0 = false; 1 = true) Integer types

sbyte – 1 byte (-128 to 127) byte – 1 byte (0 to 255) short – 2 bytes (-32768 to 32767) ushort – 2 bytes (0 to 65535) int – 4 bytes (-231 to 231 - 1) uint – 4 bytes (0 to 232 - 1) long – 8 bytes (-263 to 263 - 1) ulong – 8 bytes (0 to 264 – 1) char – 2 bytes; Unicode characters w/decimal

values 0 to 65535

Page 8: Streams and files

C# 8

C# types (2)

Floating-point (decimal) types float – 4 bytes; approx. 6 decimal digits

precision double – 8 bytes; approx. 15 decimal

digits precision Other struct and class types

depends on the struct or class definition (could be huge).

Page 9: Streams and files

C# 9

C# Streams

2 major sets of stream classes Byte streams – read/write individual bytes

Corresponds to physical data – network and disk I/O streams

Low-level

Character streams – 2-byte Unicode characters Primary text input/output stream classes

Page 10: Streams and files

C# 10

Basic Abstract stream classes

Byte stream: Stream Character streams: TextReader, TextWriter

Page 11: Streams and files

C# 11

Basic Reader/Writer Operations Reader

int Read();// return Unicode value of next // character

string ReadLine();// return a line of text

Convention: returns -1 if no data available (end of file)

Writervoid Write(char c); // write character c

void WriteLine(string s);// write string s

All can throw IOExceptions Normally throws a specific subclass of IOException

depending on the actual error

Page 12: Streams and files

C# 12

File I/O Idea: Create a data object that manages the file

stream Member functions support input and output operations Files normally opened when these objects are created Close files explicitly when done to be sure things

terminate cleanly

Basic classes FileStream derived from Stream StreamReader derived from TextReader StreamWriter derived from TextWriter

Page 13: Streams and files

C# 13

Copy File One byte at a Time

class FileCopy {

public static void Main() {

FileStream inFile = new FileStream(@“c:\source.txt”, FileMode.Open, FileAccess.Read);

FileStream outFile = new FileStream(@“c:\sink.txt”, FileMode.OpenOrCreate, FileAccess.Write);

int b;//current byte (an int since it can be -1 for EOF)

b = inFile.ReadByte();

while (b != -1) { // end of file?

outFile.WriteByte(b);

b = inFile.ReadByte();

}

inFile.Close();

outFile.Close();

}

}

Page 14: Streams and files

C# 14

Critique

Problems with this? Very low-level; would like to work with more

convenient chunks like lines of text Not very useful to hard-wire file names into

the code What about possible exceptions? See full code on the class web site

Page 15: Streams and files

C# 15

Command Line Arguments Arguments can be supplied on command line when

program is executedFileCopy c:\input.txt c:\output.txt

These values are found in the String array parameter to mainpublic static void Main(String[] args) {

if (args.length != 2) {

Console.WriteLine

(“Must have 2 file names for arguments”);

return;}

// open files using names in args[0] and// args[1], etc...

Page 16: Streams and files

C# 16

Higher-Level Input – StreamReader

Can be wrapped around a Stream, or can be created directly from a file

Provides ReadLine() method to read next line and return it as a single stream Returns null if end-of-file reached Handles newline portability problems – don’t try to

handle newlines yourself; take advantage of thisFileStream inFile = new FileStream(fileName, FileMode.Open, FileAccess.Read);

StreamReader sr = new StreamReader(inFile);String line = sr.readLine();

// Could do new StreamReader(fileName)

Page 17: Streams and files

C# 17

StreamWriter

Same as StreamReader but for output WriteLine(s); // write a string on one line

Page 18: Streams and files

C# 18

Exception Handling

Most I/O functions can throw subclasses of IOException

Good practice – handle common cases and generate a user-friendly error message Input file not found Unable to open output file etc.

Page 19: Streams and files

C# 19

BinaryReader and Writer

A wrapper of FileStream able to deal directly with basic types (int, double, etc…)

Use the methods ReadBoolean, ReadInt, etc… for input

Use the method Write(…) (with many overloads) for output

Useful to read and write objects from and to files. Serialization is another approach to read and write objects from and to files.