File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File...

49
File I/O Version 1.0

Transcript of File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File...

Page 1: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

File I/OVersion 1.0

Page 2: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

TopicsI/O StreamsFile I/OFormatting Text FilesHandling Stream ErrorsFile Pointers

Page 3: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Objectives

After completing this topic, students should be able to:

Write programs that correctly read text data from a file,handling file errors and end of file conditions appropriately.

Write programs that correctly format and write text datato a file.

Correctly use the C++ stream manipulation functionsin a program

Page 4: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Input/Output Streams

an ordered sequence of bytes

source

sink

We put data, as bytes, into an output stream

We take data, as bytes, out of an input stream

Page 5: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Standard I/O cin – the standard input stream cout – the standard output stream cerr – the standard error stream

These streams (objects) are automatically created for you whenyour program executes. To use them you only need to#include <iostream> and the using namespace std directive.

Page 6: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

File I/O

When a program takes input from a file, we say thatit reads from the file.

When a program puts data into a file, we say that it writes to the file.

To read or write to a file, we create a stream object, and connect it to the file by opening it.

Page 7: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Text Files

Data in a file can either be text or binary.

Everything in a text file appears as readablecharacters.

Text files are also referred to as Formatted orSequential files.

Page 8: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

The fstream classes

We use objects of the ifstream class to read from a file, and objects of the ofstream class to write toa file.

These classes are defined in <fstream>. To use themwe must write

#include <fstream>using namespace std;

Page 9: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

ifstream Functions>> overloaded stream extraction operatorget (ch) extract one character into chget (str) extract characters into array str, until ‘\n’get (str, MAX) extract up to MAX characters into array strget (str, DELIM) extract characters into array str until

DELIM character is encountered. Leave DELIM character in buffer

get (str, MAX, DELIM)

these ought to look familiar, they are the samefunctions we use on standard In and standard Out.

Page 10: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Declaring Streams

To use a stream object, it must first be declared

ifstream inStream;ofstream outStream;

Page 11: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Stream variables

A stream object is like any other variable, butthere are some important exceptions:

You cannot assign a value to a stream variable

If you pass a stream variable as a parameter, youmust pass it by reference or address.

Page 12: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Connecting a Stream to a File

ifstream inputStream;inputStream.open (“theData.txt”);

Widget 123V89001 12.95theData.txt

inputStream

to program

you can declare and connect to a file at the same time:

ifstream inputStream (“theData.txt”);

Page 13: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Paths

ifstream inputStream;inputStream.open (“theData.txt”);

if no path is specified, the file is assumedto be in the same directory as the programthat is executing.

When you code a \ in a pathname, you mustwrite \\. Why?

inputStream.open (“c:\\theData.txt”);

Page 14: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Reading From a Text File

To read from a text file, use the streamextraction operator, just as you would to read from the keyboard.

string description;string partNumber;double price;

ifstream inputStream;inputStream.open (“theData.txt”);…inputStream >> description >> partNumber >> price;…

Page 15: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Type Safe I/O

In the C programming language, input and outputare done with very different libraries than thoseused in C++ (Although you can still use the C I/Olibraries in C++ if you want to).

One of the advantages to using the new C++ librariesis that C++ I/O is typesafe. The << and >> operators areoverloaded to do the correct thing for all of the standarddata types.

These operators can also be overloaded for user defineddata types.

Page 16: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Widget 123V89001 12.95theData.txt

inputStream

Data is read from the file and converted intothe appropriate data type.

double price;inputStream >> price;

in the file, this ischaracter data.

price

convert fromcharacter to double

12.95

…111000011010…

Page 17: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Records and Fields

Data in a text file is often organized into field and records.

Widget 123V89001 12.95 \nSprocket 456Y79321 21.50 \nZagget 678H0032 32.25 \nSpoolbot 345W2311 3.23 \n……

fields are usually separated by spaces,but may be separated by other delimiters,such as a comma or tab

records are usually separated bynewline characters, but may beseparated by other delimiters, suchas semicolons.

it is important to know how data in a fileis organized, or it cannot be read.

Keep in mind when the stream extraction operator stops reading!

Page 18: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Writing to a Text File

Use the stream insertion operator to write to a text file,just as if you were writing to the display.

ofstream outputStream;outputStream.open (“theData.txt”);

outputStream << price;

Page 19: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Opening an Output file

If the named file does not exist, the file is created.

If the named file already exists, it is opened, andthe contents of the file are discarded, by default.

Page 20: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Formatting the Output

Most of the time, when we write data to a file, it iswith the idea in mind that the data will be read infrom this or some other program.

It is up to the programmer to format the data in theoutput file, so that it can later be read in a meaningfulway.

Page 21: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Example

int a = 5;int b = 15;int c = 239;

ofstream myOutputStream (“mydata.txt”);myOutputStream << a << b << c;

515239

What happens when you try to read this file?

Page 22: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

int a = 5;int b = 15;int c = 239;

ofstream myOutputStream (“mydata.txt”);myOutputStream << a << “ “ << b << “ “ << c;

add white space toseparate the fields!

Page 23: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Closing the File

It is good programming practice to close a fileas soon as you are done using it.

myOutputStream.close ( );

Although a file is (usually) closed automatically when aprogram ends normally, it is not closed if an erroroccurs and the program terminates abnormally.If the file is not closed, all of the data written tothe file is lost!

Page 24: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Mode Bits

When a file is opened, you can supply bits that furtherdefine the file. These mode bits are defined in the iosclass. The ios class contains a number of importantconstants we use in file I/O.

ios::in open the file for reading, the default for ifstreamios::out open the file for writing, the default for ofstreamios::app open the file for appending. All data is written at the end of the fileios::trunc open the file and discard contents, the default for ofstream

ios::binary open the file for binary content, Note there is no ios::text which is the default

Page 25: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

openmode Bits

ios::app - seek to the end of a stream before each insertion.ios::ate - seek to the end of a stream when its controlling object is first created.ios::binary - read a file as a binary stream, rather than as a text stream. Default is text; however there is no ios::text mode bit.ios::in - permit extraction (read) from a stream.ios::out - permit insertion (write) to a stream.ios::trunc - delete contents of an existing file when its controlling object is created or create the file if it doesn’t exist.

Page 26: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Example

#include <fstream>using namespace std;

ofstream myOutputStream (“TheData.txt”, ios::app);

Page 27: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Stream StatesObjects of all of the stream classes have a state thatexpresses the condition of the stream..

The stream classes provide functions to query thestream’s state.

good( ) Everything’s fineeof( ) An input operation tried to read beyond the end of the filefail( ) An input operation failed to read the expected character, or an output operation failed to generate the desired charactersbad( ) Indicates the loss of integrity of the underlying input or output sequencerdstate( ) Returns all the stream state bits

eoffailbad

2 1 0

Page 28: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Checking that a File Opened

In C++, errors are not reported unless the programmerexplicitly asks. For example, your program could callfor a file to be opened and then read data from the file.If the file does not exist, no error is reported and youthink that everything worked fine!

Page 29: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

ifstream myInputStream;myInputStream.open (“someData.txt”);

if (myInputStream.rdstate( )!=0){ cout << “Could not open file”;}else{ …

check the state of thestream here…

We could also write

if (!myInputStream) {

Page 30: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Because I/O is subject to so many errors,it is good programming practice to check

the state of the stream after every I/O operation!

Page 31: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Checking for End of Fileint theData;istream myFile;

myFile.open (“someData.txt”);

while (!myFile.eof( )){ myFile >> theData; …}

when attempting to readpast the end of the file, the eof( ) function returns true.But note that the condition isnot checked until you go backto the while statement!

Could also have written while (myFile >> theData){ …}

Page 32: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

File Names as Input

char fileName[80];ifstream myData;cout << “Enter in a file name: “;cin >> fileName;myData.open (fileName);…

the filename must be storedin an array of characters. Wewill talk about char arraysin a later section…

Alternatively you could writestring fileName;cin >> fileName;myData.open(fileName.c_str( ) );

Page 33: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Precision

Precision refers to the number of digits afterthe decimal point.

Every output stream has a member functionnamed precision, that sets the precision ofthe data that goes into the file.

outPutStream.precision ( 3 );

Precision stays as set until changed by anothercall to the precision function.

Page 34: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Formatting Flags

Formatting flags are defined in the ios class.

Stream classes have a member function,setf( flag ) that sets these formatting flags.

left left align output not setright right align output setdec output as decimal sethex output as hexadecimal not setoct output as octal (base 8) not setshowpoint show decimal point on output not setscientific output in exponential format not setfixed output in fixed format (not scientific) not set

Page 35: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

You can combine flags with the | operator

myStream.setf (ios::fixed | ios::showpoint);

A flag remains set until it is unset.

myStream.unsetf (ios::fixed);

Page 36: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Stream Manipulators

Stream manipulators go directly into the stream.They are inserted using the stream insertion operator

dechexoctendlsetw (w)setprecision (n);setiosflags (flags);setfill (fillChar);

myStream << setw (5) << theData;

Page 37: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Side Effects

You don’t want a function to have an unwanted side effect.One example would be setting I/O flags in a function andleaving them that way when you exit the function.

The function flags returns a long data type that contains the settings of all of the I/O flags.

long myFlags = myStream.flags ( );…

myStream.flags (myFlags);

without an argument the function returns the flags.

with an argument, the flags are restored to those set in the parameter.

Page 38: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

File PointersStreams have pointers associated with them

get pointer points to the place next character will be read from put pointer points to where the next character will be written

tellg( ) returns current get (read) file pointertellp ( ) returns current put (write) file pointer

seekg ( ) positions get (read) file pointerseekp ( ) positions put (write) file pointer

Page 39: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

seekp (15); move 15 bytes from start of file (default)

seekp (-10, ios::end);move -10 bytes from end of file

seekg (6, ios::cur); move 6 bytes from current position

Page 40: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Updating Sequential Files

When updating sequential files, you cannot dependon the size of a record always being the same. So, you must locate the position where you want to startwriting, and then rewrite the remainder of the file.

Page 41: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Binary I/O

Data is written to the output device exactly as itIs stored in memory.

Binary I/O is done with the functions * read( ) * write( )

The parameters are the address of the data bufferand the number of bytes to read or write.

The address must be cast to a char*

Page 42: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Example

// buff is the address of an array of MAX integers…

ofstream os(“myData.dat”, ios::binary);os.write(reinterpret_cast<char*>(buff), MAX * sizeof(int) ); oros.write((char*)buff, MAX * sizeof(int) );os.close( );

reinterpret cast tells the compilerthat you want to do this cast, eventhough it might not make sense tothe compiler.

Page 43: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

buff

100110… …10100

buff + MAX

Page 44: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

#include <iostream>using namespace std;int main( ){ int anInteger; // temp holding place for input do { cout << "\nType an integer ( 0 to quit ):"; cin >> anInteger; cout << "You typed " << anInteger;

} while ( anInteger != 0 );

return 0;}

Page 45: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Handling I/O Errors – An Exampleint main( ){ int anInteger; // temp holding place for input do { cout << "\nType an integer ( 0 to quit ):"; if ( cin >> anInteger ) { cout << "You typed " << anInteger; }

else { cout << "\nBad input ... Integer expected!"; cin.clear ( ); cin.sync ( ); } } while ( anInteger != 0 );

return 0;}

Page 46: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Practice

Given: You have a file of student grades onyour c: drive. The path to the file is

c:\grades.txt

The file is a text file.

Write the statement that declares the input stream object mydata, opens the file, and connects it to the stream object.

Page 47: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

Practice

Write the code that tests to see if the file openedsuccessfully. If it did not open, output a messageto the user.

Page 48: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

PracticeNow . . . Put all of this code in a loop that1) Prompts the user for a file name2) Creates the stream object and tries to open the file3) Tests to see if the file opened successfully4) If it did not open send a message to the user to a) exit the program, or b) type in a different file name c) accept only valid choices in response5) When the file opens, tell the user

hint: draw an activity diagram first!

Page 49: File I/O Version 1.0. Topics I/O Streams File I/O Formatting Text Files Handling Stream Errors File Pointers.

PracticeThe file contains a set of integers, withone integer on each line of the file.

We want to add up all of the value in the file.

Write a loop that will read each integer valuefrom the file and add it to a variable myData.

You do not know how much data is in the file.

Print a message to the user if any read operationfails because of bad data.