an equal opportunity university cs 215 lecture 8 i/o streams, error handling & file stream...

95
An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Upload: johnathan-mervin-hunt

Post on 30-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

An Equal Opportunity University

CS 215Lecture 8

I/O Streams, Error Handling & File

StreamIsmail Abumuhfouz

Page 2: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Streams• You have seen two streams so far: cin and cout• A stream is how C++ represents something you can

read input from or write output to.– The keyboard and console window, a file (chapter 8),

some hardware devices.– Usually either standard input/output, or a file.

• Output streams are pretty simple.– Use the insertion operator to do output: cout << value;– Use manipulators like setw() and scientific to

control the• formatting of subsequent fields.• Input streams are more complex

Page 3: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams

• If we define a variable called intvar as:– int invar;

• What happens when you do cin >> intvar;?– Read input from the keyboard, but what if the

user hasn't typed anything?– Wait for something to be typed, but how much?

Page 4: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams

• If we define a variable called intvar as:– int invar;

• What happens when you do cin >> intvar;?– Read input from the keyboard, but what if the

user hasn't typed anything?– Wait for something to be typed, but how much?– A whole line!!! but we only need one integer.

• What is a line?

Page 5: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams• If we define a variable called intvar as:

– int invar;• What happens when you do cin >> intvar;?

– Read input from the keyboard, but what if the user hasn't typed anything?

– Wait for something to be typed, but how much?– A whole line!!! but we only need one integer.– What is a line?

• A Line is Everything up to a newline character ‘\n'

Page 6: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams• int invar;• What happens when you do cin >> intvar;?

– Read input from the keyboard, but what if the user hasn't typed anything?

– Wait for something to be typed, but how much?– A whole line!!! but we only need one integer.– What is a line?

• A Line is Everything up to a newline character ‘\n‘• Input a line from the user.• From the data we have read, skip over the whitespace.• Then read characters until we have a complete number.• Convert that into an integer and store it in intvar.• Is anything left over?

Page 7: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams• int invar;• What happens when you do cin >> intvar;?

– Read input from the keyboard, but what if the user hasn't typed anything?

– Wait for something to be typed, but how much?– A whole line!!! but we only need one integer.– What is a line?

• A Line is Everything up to a newline character ‘\n‘• Input a line from the user.• From the data we have read, skip over the whitespace.• Then read characters until we have a complete number.• Convert that into an integer and store it in intvar.• Is anything left over?• The leftover data is buffered (temporarily saved).• The next input operation will process the leftover data, and read• another line if necessary

Page 8: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams• Reading a single word is straightforward:

– string word;– cin >> word;– Skips whitespace, reads a number of non-whitespace

characters.– Stops just before the next whitespace.

• What if we want to read an entire name?– Not all names have two (or three) words

Page 9: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams• Reading a single word is straightforward:

– string word;– cin >> word;– Skips whitespace, reads a number of non-whitespace characters.– Stops just before the next whitespace.

• What if we want to read an entire name?– Not all names have two (or three) words– What if we want to read an entire name?– Not all names have two (or three) words.– Let's read a whole line- everything up to the newline.

• string line;• getline(cin, line);

– Reads the newline, but throws it away.– Be sure to #include <string>

Page 10: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams

Page 11: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input Streams

Page 12: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Fix It

Page 13: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Dump Users & Bad Inputs• We cant control the user reaction with our program.

• We assume that we are dealing with “Dump Users” and we are trying to react with their unpredicted actions.

• Our programs should be able to apply validation and verification process of input and process data before we continue with the next coding.

• Users may enter bad inputs, they may enter textual data for numerical ones or do something similar.

• Our program should be able to handle that or any possible cases. Sometime we have huge number of cases.

Page 14: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Dump Users & Bad Inputs• What happens if the user gives bad input to cin >> intvar ?

– Like typing “Alex” OR “125.63” OR Press Enter Or a value outside the boundaries of the int OR Other cases.

Page 15: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Dump Users & Bad Inputs• What happens if the user gives bad input to:

cin >> intvar ? • This puts cin into a failing state .

–Further attempts at input do nothing!–You can detect the failing state with bool cin.fail().–You can clear it with void cin.clear().–The bad input is still buffered: better skip it with cin.ignore()

• Check the following example.

Page 16: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Fixing Bad Inputs.

Page 17: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Dump Users & Bad Inputs• If we are inside a failing state from using cin,

then:• You can detect the failing state with bool

cin.fail():• Check if it returns true then you made an error,

else you did not.• You can clear it with void cin.clear().• But the bad input is still buffered: better skip it

with void cin.ignore().

Page 18: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Checking Data

Function Meaning

isalnum(int) Returns non-zero if the parameter is a letter or a digitisalpha(int) Returns non-zero if the parameter is a letterisdigit(int) Returns non-zero if the parameter is a digitisspace(int) Returns non-zero if the parameter is whitespace

isxdigit(int) Returns non-zero if the parameter is a hexadecimal digit (0-9, a-f, A-F)

ispunct(int) Returns non-zero if the parameter is neither alphanumeric nor whitespace

Inside the Library #include <cctype>, use any of the following function to validate your data

Page 19: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

String Validations *

*: http://www.learncpp.com/cpp-tutorial/135-stream-states-and-input-validation/

Page 20: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

String Validations

Page 21: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

String Validations • What happens if the we want to match specific case for

an input?• For example when we are validating a phone number

usually we follow a specific template :(###) ###-####

• How we can make sure that if we ask the user to input a string which represent a phone number, then what the user input is valid comparing to the provided template.

• Lets check the following example.

Page 22: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Validations

Page 23: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Validations

Page 24: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Validation of Numerical Data• What happens if the we want to validate a numeric

values? What we can do?• We have two ways to do that:

1. By Using input stream checking using: cin.fail(), cin.clear(), c.ignore() and cin.gcount().

2. By entering the numerical data as string then checking the validity of each character to be digit then converting this string -after making sure it is holding only numeric digits- to numeric value.

3. Check the following exmaples.

Page 25: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Validation of Numerical Data: First Way

We can use the gcount() function to determine how many characters were ignored.If our input was valid, gcount() should return 1 (the newline character). If it returns more than 1, the user entered something that wasn’t extracted properly (e.g: “34abcd56”).

Page 26: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Validation of Numerical Data: Second Way

*: http://www.learncpp.com/cpp-tutorial/135-stream-states-and-input-validation/

Page 27: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Validation of Numerical Data: Second Way

To use stringstream you have to #include <sstream> Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without an real I/O channel.Check: http://www.learncpp.com/cpp-tutorial/134-stream-classes-for-strings/

Page 28: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Exceptions

• Exceptions provide another way to report and handle errors. • An exception is just a C++ object: it can be anything!• Usually we use standard exception classes from <stdexcept> :

– runtime error , length error , range error.• The code that detects the error throws an exception:

– throw runtime error("invalid character");– throw length error("negative size provided");– throw 23; // Not recommended, but allowed.

• By default, this terminates the program!

Page 29: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Exceptions• We usually prefer to handle erroneous conditions rather than

terminating the program. We do this by catching the exception.

• When an exception is thrown: – Each function in progress, in turn, gets a chance to catch

it.– This function, then its caller, then its caller's caller, etc. – If one of them does catch the exception, it is handled:– Execution continues after the code that handles the

exception.– If even main didn't catch it, terminate.

Page 30: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Syntax of Catching Exceptions

Page 31: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Exceptions• We can actually catch different types of exceptions and

handle them in different ways.• The catches are tried in order until one matches the

exception's type.• If one of them caught the exception, continue after the

catches.• Otherwise, or if we re-throw, the exception goes to our caller,

etc

Page 32: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Files

Page 33: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

What is File?

• A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.

• All files are assigned a name that is used for identification purposes by the operating system and the user

Page 34: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Input / Output (I/O)• I/O = Input/Output• In this context it is input to and output from programs• Input can be from keyboard or a file• Output can be to display (screen) or a file• Advantages of file I/O

– permanent copy– output from one program can be input to another– input can be automated (rather than entered manually)

Page 35: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Streams• Stream: an object that either delivers data to its destination

(screen, file, etc.) or that takes data from a source (keyboard, file, etc.)– it acts as a buffer between the data source and destination

• Input stream: a stream that provides input to a program• Output stream: a stream that accepts output from a program

– cout is an output stream– cin is an input stream

• A stream connects a program to an I/O object– cout connects a program to the screen– cin connects a program to the keyboard

Page 36: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Files• The C++ input/output library is based on the

concept of streams. (iostream)– An input stream is a source of data.– An output stream is a destination for data.– The most common sources and destinations for data

are the files on your hard disk.

Page 37: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Files Types• In C++ we are dealing with two kinds of files:

– Text Files• lab1.c - text file• lab1.data - text file

– Binary Files. • Microsoft Word Document• MP3, Pictures and others.

Page 38: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Binary versus Text files• All data and programs are ultimately just zeros and ones

– each digit can have one of two values, hence binary– bit is one binary digit, while a byte is a group of eight bits

• Text files: the bits represent printable characters– one byte per character for ASCII, the most common code– for example, C++ source files are text files– so is any file created with a "text editor"

• Binary files: the bits represent other types of encoded information, such as executable instructions or numeric data– these files are easily read by the computer but not humans– they are not "printable" files

• actually, you can print them, but they will be unintelligible• "printable" means "easily readable by humans when printed"

Page 39: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

What Do You Need to Include with Files• Buffer - a temporary storage area used to transfer

data back and forth between memory and auxiliary storage devices.

• Stream - files are manipulated in C++ with streams, a stream can be consider as a mechanism that is connected to a file that allows you to access one element at a time.

Page 40: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Streams• Stream: an object that either delivers data to its destination

(screen, file, etc.) or that takes data from a source (keyboard, file, etc.)– it acts as a buffer between the data source and destination

• Input stream: a stream that provides input to a program• Output stream: a stream that accepts output from a program

– cout is an output stream– cin is an input stream

• A stream connects a program to an I/O object– cout connects a program to the screen– cin connects a program to the keyboard

Page 41: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

What Do You Need to Include with Files• To read or write disk files, you use variables.

– ifstream for input from plain text files.– ofstream for output to plain text files.– fstream for input and output from binary files

Page 42: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Steps Needed to Deal with Files1. Define the stream’s header.2. Define an object of that stream 3. Open the file4. Read/Write/Process the file contents.5. Close the file.

Page 43: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Operations On Text File

Page 44: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Step 1: Streams Headers

1. For input from plain text files. #include <ifstream>

2. For output to plain text files #include <ofstream>

3. For input and output from binary files #include <fstream>

Page 45: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

• The first step in opening a file is having the stream variable ready.

• Here’s the definition of an input stream variable named in_file:

ifstream in_file;

OR:

• Here’s the definition of an ouput stream variable named out_file:

ofstream out_file;

OR:

• Here’s the definition of an input/output stream variable named bininout_file:

ofstream bininout_file;

Step 2: Creating a File Stream Object

Page 46: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

• The process here is similar to define a varaible.

• The only thing new for you is the data type

• The name here which is in_file or out_file or bininout_file, is not the name of the actual file we are trying to connect to, but instead, consider it as a variable name in our code which point to that file.

Step 2: Creating a File Stream Object

Page 47: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Here we use the method (function) open, and we have two ways to open a file:

• Encoded the name of the actual file in the code:– in_file.open("input.dat");

• OR:

• Asking for the name of the file/Passing it as a paramter (in case we are in a function)– string fileName;

– getline(cin,fileName);

– in_file.open(fileName.c_str());

Step 3: Opening the File

Page 48: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

File names can contain directory path information, such as:

UNIXin_file.open("~/nicework/input.dat");

Windowsin_file.open("c:\\nicework\input.dat");

Opening a File

Similar to \n

When you specify the file name as a string literal, and the name contains backslash characters (as in a Windows path and filename), you must supply each backslash twice to avoid having escape characters in the string

Page 49: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

No Need to specify the path of the file if we included it in our solution (project) at the same location where we save our solution.

Here is how we do that in visual studio c++

Adding File to Project Solution

Page 50: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Every File Has Two Names• The code to open the file creates two names for an output file

– the name used by the operating system• numbers.dat in the example

– the stream name• in_file in the example

• C++ programs use the stream name– in_file in the example

Page 51: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Warning When Opening a FileFile Type Default Open Mode

o fs tre a m The file is opened for output only. (Information may be written to the file, but not read from the file.) If the file does not exist, it is created. If the file already exists, its contents are deleted (the file is truncated).

ifs tre a m The file is opened for input only. (Information may be read from the file, but not written to it.) The file’s contents will be read from its beginning. If the file does not exist, the open function fails.

Page 52: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Testing the Opening Process

• To test if you successfully opened the file use the method fail(): if (in_file.fail()) cout<<“Error opening file\n”;

Page 53: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Step 5: Closing the File

• An Input/Output file should be closed when you are done dealing with it.

• To close the ifstream stream use the method close().

in_file.close();

• To close the ofstream stream use the method close().

out_file.close();

• If a program ends normally it will close any files that are open, but do you guarantee that it will close normally??!!

Page 54: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

If It Is Done Automatically, Why Explicitly Close Files?If a program automatically closes files when it ends normally, why close them

with explicit calls to close?

Two reasons:

1. To make sure it is closed if a program ends abnormally (it could get damaged if it is left open).

2. A file open for writing must be closed before it can be opened for reading.

Page 55: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Where is Step 4!!!?We jumped from 3 to 5.

Step 4 represents the real work on file

Page 56: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Step 4: Read/Write/Process File

After opening the file and before closing it, we are trying to do some processing on the file.

We may want to read something from it.We may want to write something on it.We may need to do both (but not at the same time).

Lets See how we can do that…..

Page 57: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Step 4: Read From a File

After opening the file and before closing it, we are trying to do some processing on the file.

We may want to read something from it.We may want to write something on it.We may need to do both (but not at the same time).

Lets See how we can do that…..

Page 58: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

You already know how to read and write using files.

Yes you do:

string name;

double value;

in_file >> name >> value;

Similar to cin >>, here you read from the file and store what you read in name and then value

Step 4: Reading from a Stream using >>

Page 59: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

You already know how to read and write using files.

Yes you do:

double value;

out_file << “Hello “ << value;

Similar to cout <<, here you write to the stream hello and the value of value ,

Step 4: Writing to the Stream using <<

Page 60: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Working with File Streams

Page 61: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Functions need to be able to process files too, and there’s an easy rule to follow:

As parameters, streams are ALWAYS passed by reference.

(Did you notice that “ALWAYS”?)

Passing Streams to Functions

Page 62: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

What really happens when reading a string?

string word;in_file >> word;

1. If any reading can be done at all, all whitespace is skipped(whitespace is this set: '\t' '\n' ' ').

2. The first character that is not white space is added to the string word. More characters are added until either another white space character occurs, or the end of the file has been reached.

Reading strings

Page 63: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

It is possible to read a single character – including whitespace characters.

char ch;in_file.get(ch);

The get method also returns the “not failed” condition so:

while (in_file.get(ch)){ // Process the character ch}

Reading Characters

Page 64: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

The get method makes it possible to process a whole file one character at a time:

char ch;while (in_file.get(ch)){ // Process the character ch}

Reading the Whole File Character by Character

Page 65: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Remember cctype???

Reading the Whole File Character by CharacterWhy???

Page 66: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

The function (it’s not a method):getline()

is used to read a whole line up to the next newline character.

Reading A Whole Line: getline

Page 67: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

stream to read from string to read into

getline(in_file, line);

stops at '\n', takes it from the stream and throws it away – does not store it in string

Reading A Whole Line: getline

Page 68: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

• Until the next newline character, all whitespace and all other characters are taken and stored into the string – except the newline character – which is just “thrown away”

• The only type that can be read into is the string type.

string line;

getline(in_file, line); // stops at '\n'

Reading A Whole Line: getline

Page 69: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

The getline function, like the others we’ve seen, returns the “not failed” condition.

To process a whole file line by line:

string line;

while( getline(in_file, line))

{

// Process line

}

Reading A Whole Line: getline

Page 70: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

What about a single character?The put method:

out_file.put(ch);

Writing Text Output

Page 71: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Formatting Output – Manipulators

Page 72: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Operations On Binary File

Page 73: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Same Steps Needed to Deal with Files1. Define the stream’s header.2. Define an object of that stream 3. Open the file4. Read/Write/Process the file contents.5. Close the file.

But different code

Page 74: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Binary File and Random Access

It doesn’t really mean random as in srand and rand and that sort of processing!

Random means that you can read and modify any item stored at any location in the file – directly going to it.

To get to the 42nd item in the file you don’t have to read all 41 items before it.

Page 75: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Random Access

Random access means: Not standing in a line,

And you can start with the cake!

Page 76: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Sequential Access and Random Access

Page 77: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Random Access

The screen has a cursor so that the user knows where she is typing.

Files have two special positions:the put position – where the next write will go.the get position – where the next read will be.

Page 78: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Random AccessThe 0 will be overwritten next.

The 2 will be read next.

Page 79: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Random Access To change the get positions, you use this method:

strm.seekg(position);

seekg means move the get position “g” as in “get” – get it?

The parameter value is how many bytes from the beginning of the file to move the get position to.

Page 80: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Random Accessseekp does the same for the put position

strm.seekp(position);

Page 81: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Random AccessYou can also find out where these positions currently are:

g_position = strm.tellg();p_position = strm.tellp();

Page 82: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Binary FilesMany files, in particular those containing images and sounds,

do not store information as text but as binary numbers.

The meanings and positions of these binary numbers must be known to process a binary file.

Page 83: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Opening Binary Files To open a binary file for reading and writing, use this version of the open method:

fstream strm; strm.open("img.gif", ios::in | ios::out | ios::binary);

That’s the “vertical bar”

• ios::in and ios::out allow us to read from and write into the same file.

• For plain files we could do only one or the other.• The ios::binary means it is a binary file

– the capital backslash.

Page 84: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Opening Binary Files To read from a binary file you cannot use the >> operator

Use the get method:

int input = strm.get();

In a binary file stream, this reads one byte as a number, a value between 0 and 255.

Page 85: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Opening Binary FilesA “real” int, like 1822327, takes four bytes to store on most systems.

To read a “real” int, you will have to do four reads

Page 86: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image FilesTo process image files, or any binary file,

you must know how everything is arranged in the file.

Page 87: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File Format

The BMP file format for 24-bit true color format:

Each pixel’s color is representedin RGB form – Red, Green, and Blue amounts.

In the file, each pixel is represented asa sequence of three bytes:

• a byte for the blue value (B)• a byte for the green amount (G)• a byte for the red amount (R)

Page 88: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File Format

Here are some RGB values stored in a BMP file (you’ll notice that it’s really stored as BGR):

Cyan (a mixture of blue and green) is the bytes: 255 255 0

Pure red is the values: 0 0 255 (no blue, no green, all red)

Medium gray is 128 128 128 (half of 255 for all three)

Page 89: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP HeaderMost files start with some information aboutthe contents called the header.

A BMP file is no different:

Page 90: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File Format

The image itself is represented as a sequenceof pixel rows (a scan line),starting with the bottom row in the image.

Each pixel row contains a sequence of BGR bytes.

The end of the row is padded with additional bytes sothat the number of bytes in the row is divisible by 4.

Page 91: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File Format For example,

if a row consisted of merely three pixels, one cyan, one red, one medium gray, there would three padding bytes.

The numbers would be:

255 255 0 0 0 255 128 128 128 x y z

Page 92: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File Format

one cyan, one red, one medium gray one, one padding.

255 255 0 0 0 255 128 128 128 x y z

Page 93: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File FormatThere would be

height scans lineseach width * 3 bytes long

(rounded up to a multiple of 4)

height

...

Page 94: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File Format

Example: write code to create the negative of an input image file:

Page 95: An Equal Opportunity University CS 215 Lecture 8 I/O Streams, Error Handling & File Stream Ismail Abumuhfouz

Processing Image Files: The BMP File Format

We will create the negative of each pixel bysubtracting the R, G, and B values from 255.

Of course that will be a function!

Check the following Example.