+ All Categories
Home > Documents > Working with Files

Working with Files

Date post: 02-Jan-2016
Category:
Upload: leah-buckley
View: 17 times
Download: 2 times
Share this document with a friend
Description:
Working with Files. File Input and Output Stream. C++ uses file streams as an interface between the programs and the data files. Input Stream. Data input. Read Data. Disk Files. Program. Output Stream. Write Data. Data output. File Input and Output Stream. - PowerPoint PPT Presentation
30
Learners Support Publication www.lsp4you.co Working with Files Working with Files
Transcript
Page 1: Working with Files

Learners Support Publicationswww.lsp4you.com

Working with FilesWorking with Files

Page 2: Working with Files

Learners Support Publicationswww.lsp4you.com

File Input and Output StreamFile Input and Output Stream

C++ uses file streams as an interface C++ uses file streams as an interface between the programs and the data files.between the programs and the data files.

Disk Files Program

Output Stream

Data output

Data inputInput Stream

Write Data

Read Data

Page 3: Working with Files

Learners Support Publicationswww.lsp4you.com

File Input and Output StreamFile Input and Output Stream

Disk Files Program

Output Stream

Data output

Data inputInput Stream

Write Data

Read Data

The stream that supplies data to the program is known as input stream

The stream that receives data from the program is known as output stream

Input stream extracts (or read) data from file

Output stream inserts (or writes) data to the file

Page 4: Working with Files

Learners Support Publicationswww.lsp4you.com

Opening FilesOpening Files

For opening a file, we must first create a file For opening a file, we must first create a file stream and then link it to the filename.stream and then link it to the filename.

A file stream can be defined using the classes A file stream can be defined using the classes ifstream, ofstream, and fstream that are ifstream, ofstream, and fstream that are contained in the header file fstream.contained in the header file fstream.

The class to be used depends on read or write.The class to be used depends on read or write. A file can be open in two ways:A file can be open in two ways:

Using the constructor function of the class.Using the constructor function of the class.• Useful when we use only one file in the stream.Useful when we use only one file in the stream.

Using the member function open( ) of the class.Using the member function open( ) of the class.• Use to manage multiple files using one stream.Use to manage multiple files using one stream.

Page 5: Working with Files

Learners Support Publicationswww.lsp4you.com

Opening Files Using ConstructorOpening Files Using Constructor

This involves two steps:This involves two steps: Create a file stream object to manage the Create a file stream object to manage the

stream using appropriate class.stream using appropriate class.

• The class ofstream used to create output stream.The class ofstream used to create output stream.• The class ifstream to create input stream.The class ifstream to create input stream.

Initialize the file object with the desired Initialize the file object with the desired filename.filename.

Page 6: Working with Files

Learners Support Publicationswww.lsp4you.com

Opening Files Using ConstructorOpening Files Using Constructor

ofstream outfile (“results”);ofstream outfile (“results”); ifstream infile(“data”);ifstream infile(“data”);

continue …

Program

Output Stream

outfile

infile

Input Stream

Disk

ResultFile

DataFile

Page 7: Working with Files

Learners Support Publicationswww.lsp4you.com

Opening Files Using Open( )Opening Files Using Open( )

The open( ) can be used to open multiple The open( ) can be used to open multiple files that use the same stream object.files that use the same stream object.

For processing a set files sequentially.For processing a set files sequentially.

file-stream-class stream-object;

stream-object.open ( “file_name” );

Page 8: Working with Files

Learners Support Publicationswww.lsp4you.com

Opening Files Using Open( )Opening Files Using Open( )

ofstream outfile;ofstream outfile;outfile.open(“DATA1”);outfile.open(“DATA1”);…………....outfile.close( );outfile.close( );outfile.open(“DATA2”);outfile.open(“DATA2”);………………outfile.close( );outfile.close( );.................. The above program segment opens two files in The above program segment opens two files in

sequence for writing the data. sequence for writing the data. The first file is closed before opening the second one. The first file is closed before opening the second one. A stream can be connected to only one file at a time.A stream can be connected to only one file at a time.

continue …

Page 9: Working with Files

Learners Support Publicationswww.lsp4you.com

Detecting End-Of-FileDetecting End-Of-File

while (fin)while (fin) An ifstream object fin returns a value 0 if any error An ifstream object fin returns a value 0 if any error

occurs in the file operation including the end-of-file occurs in the file operation including the end-of-file condition.condition.

So the while loop may terminates when fin returns a So the while loop may terminates when fin returns a value of zero on reaching the end-of-file condition.value of zero on reaching the end-of-file condition.

if(fin1.eof() != 0) {exit(1);}if(fin1.eof() != 0) {exit(1);} eof( ) is a member of ios class.eof( ) is a member of ios class. It returns a non-zero value if the end-of-file (EOF) It returns a non-zero value if the end-of-file (EOF)

condition is encountered, and a zero, otherwise.condition is encountered, and a zero, otherwise.

Page 10: Working with Files

Learners Support Publicationswww.lsp4you.com

File ModesFile Modes

stream-object.open(“file_name”, mode);stream-object.open(“file_name”, mode); The second argument mode specifies the The second argument mode specifies the

purpose for which the file is opened.purpose for which the file is opened.

Default values for these second parameters:Default values for these second parameters:• ios::in – for ifstream - reading onlyios::in – for ifstream - reading only

• ios::out – for ofstream - writing onlyios::out – for ofstream - writing only

Page 11: Working with Files

Learners Support Publicationswww.lsp4you.com

File ModesFile Modes

ios::appios::app Append to end-of-fileAppend to end-of-file

ios::ateios::ate Go to end-of-file on openingGo to end-of-file on opening

ios::binaryios::binary Binary fileBinary file

ios::inios::in Open file for reading onlyOpen file for reading only

ios::nocreateios::nocreate Open fails if the file does not existOpen fails if the file does not exist

ios::noreplaceios::noreplace Open files if the file already existsOpen files if the file already exists

ios::outios::out Open file for writing onlyOpen file for writing only

ios::truncios::trunc Delete the contents of the file if it Delete the contents of the file if it existsexists

fout.open(“data”, ios::app | ios :: nocreate)fout.open(“data”, ios::app | ios :: nocreate)

continue …

Page 12: Working with Files

Learners Support Publicationswww.lsp4you.com

File PointerFile Pointer

Input Pointer (get pointer)Input Pointer (get pointer) The input pointer is used for reading contents of a The input pointer is used for reading contents of a

given file location.given file location.

Output Pointer (put pointer)Output Pointer (put pointer) The output pointer is used for writing to a given file The output pointer is used for writing to a given file

location.location.

Each time an input or output operation takes Each time an input or output operation takes place, the appropriate pointer is automatically place, the appropriate pointer is automatically advanced.advanced.

Page 13: Working with Files

Learners Support Publicationswww.lsp4you.com

File Pointer – Default ActionsFile Pointer – Default Actions

When a file opened in read-only mode, the input When a file opened in read-only mode, the input pointer is automatically set at the beginning of pointer is automatically set at the beginning of the file.the file.

When a file is opened in write-only mode, the When a file is opened in write-only mode, the existing contents are deleted and the output existing contents are deleted and the output pointer is set at the beginning.pointer is set at the beginning.

When a file is opened in append mode, the When a file is opened in append mode, the output pointer moves to the end of file.output pointer moves to the end of file.

Page 14: Working with Files

Learners Support Publicationswww.lsp4you.com

Functions for Manipulations of File PointersFunctions for Manipulations of File Pointers

seekg( )seekg( ) Moves get pointer (input) to a Moves get pointer (input) to a specified location.specified location.

seekp( )seekp( ) Moves put pointer(output) to a Moves put pointer(output) to a specified location.specified location.

tellg( )tellg( ) Gives the current position of Gives the current position of the the get pointer.get pointer.

tellp( )tellp( ) Gives the current position of Gives the current position of the the put pointer.put pointer.

Page 15: Working with Files

Learners Support Publicationswww.lsp4you.com

Seek Function with Absolute PositionSeek Function with Absolute Position

infile.seekg(10);infile.seekg(10);

Moves the file pointer to the byte number Moves the file pointer to the byte number 10. The bytes in a file are numbered 10. The bytes in a file are numbered beginning from zero. Therefore, the beginning from zero. Therefore, the pointer pointing to the 11pointer pointing to the 11thth byte in the file. byte in the file.

Page 16: Working with Files

Learners Support Publicationswww.lsp4you.com

Seek Function with Specifying the OffsetSeek Function with Specifying the Offset

seekg( offset, refposition);seekg( offset, refposition); seekp( offset, refposition);seekp( offset, refposition);

The parameter The parameter offsetoffset represents the number of bytes the represents the number of bytes the file pointer is to be moved from the location specified by file pointer is to be moved from the location specified by the parameter the parameter refpositionrefposition..

The refposition takes one of the following three constants The refposition takes one of the following three constants defined in the ios class:defined in the ios class:

ios : : begios : : beg start of the file start of the file ios : : curios : : cur current position of the pointer current position of the pointer ios : : endios : : end end of the file end of the file

Page 17: Working with Files

Learners Support Publicationswww.lsp4you.com

Seek Function with Specifying the OffsetSeek Function with Specifying the Offset

fout.seekg(0, ios : : beg);fout.seekg(0, ios : : beg); Go to startGo to start

fout.seekg(0, ios : : cur);fout.seekg(0, ios : : cur); Stay at the current positionStay at the current position

fout.seekg(0, ios : : end);fout.seekg(0, ios : : end); Go to the end of fileGo to the end of file

fout.seekg(m, ios : : beg);fout.seekg(m, ios : : beg); Move to (m+1)th byte in the fileMove to (m+1)th byte in the file

fout.seekg(m, ios : : cur);fout.seekg(m, ios : : cur); Go forward by m bytes from the current positionGo forward by m bytes from the current position

fout.seekg(-m, ios : : cur);fout.seekg(-m, ios : : cur); Go backward by m bytes from the current positionGo backward by m bytes from the current position

fout.seekg(-m, ios : : end)fout.seekg(-m, ios : : end) Go backward by m bytes from the endGo backward by m bytes from the end

Page 18: Working with Files

Learners Support Publicationswww.lsp4you.com

Sequential Input and Output OperationsSequential Input and Output Operations

put( ) and get( ) Functionsput( ) and get( ) Functions

The function put( ) writes a single character to The function put( ) writes a single character to the associated stream.the associated stream.

The function get( ) reads a single charracter The function get( ) reads a single charracter from the associated stream.from the associated stream.

Page 19: Working with Files

Learners Support Publicationswww.lsp4you.com

Sequential Input and Output OperationsSequential Input and Output Operations

write( ) and read( ) Functionswrite( ) and read( ) Functions

The functions write( ) and read ( ) handle the The functions write( ) and read ( ) handle the data in binary form.data in binary form.

The values are stored in the disk file in the The values are stored in the disk file in the same format in which they are stored in the same format in which they are stored in the internal memory.internal memory.

An int takes two bytes to store its value in the An int takes two bytes to store its value in the binary form, irrespective of its size.binary form, irrespective of its size.

But a 4 digit int will take four bytes to store it But a 4 digit int will take four bytes to store it in the character form.in the character form.

continue …

Page 20: Working with Files

Learners Support Publicationswww.lsp4you.com

Sequential Input and Output OperationsSequential Input and Output Operations

Representing 2594Representing 2594

continue …

0 0 1 0 0 0 1 00 0 0 0 1 0 1 0

4952

Binary Format

Character Format

4 Bytes II

2 Bytes II

Page 21: Working with Files

Learners Support Publicationswww.lsp4you.com

Sequential Input and Output OperationsSequential Input and Output Operations

infile.read((char *) &V, sizeof(V));infile.read((char *) &V, sizeof(V));

outfile.write((char *) &V, sizeof(V));outfile.write((char *) &V, sizeof(V));

write( ) and read( ) functions take two write( ) and read( ) functions take two arguments.arguments.

First is the address of the variable VFirst is the address of the variable V Second is the length of that variable in bytes.Second is the length of that variable in bytes. The address of the variable must be cast to The address of the variable must be cast to

type type char *char * (pointer to character type). (pointer to character type).

continue …

Page 22: Working with Files

Learners Support Publicationswww.lsp4you.com

Reading and Writing a Class ObjectReading and Writing a Class Object

The read( ) and write( ) are also used to The read( ) and write( ) are also used to read from or write to the disk files objects read from or write to the disk files objects directly.directly.

The read( ) and write( ) handle the entire The read( ) and write( ) handle the entire structure of an object as a single unit, structure of an object as a single unit, using the computer’s internal using the computer’s internal representation of data.representation of data.

Only data members are written to the disk Only data members are written to the disk files.files.

Page 23: Working with Files

Learners Support Publicationswww.lsp4you.com

Updating A File : Random AccessUpdating A File : Random Access

The size of each object can be obtained using the The size of each object can be obtained using the statementstatement

int object_length = sizeof(object);int object_length = sizeof(object);

The location of a desired object, say mth objectThe location of a desired object, say mth object

int location = m * object_length;int location = m * object_length;

The location gives the byte number of the first byte of the The location gives the byte number of the first byte of the mth object.mth object.

Now we can use seekg( ) or seekp( ) to set the file Now we can use seekg( ) or seekp( ) to set the file pointer to reach this byte.pointer to reach this byte.

Page 24: Working with Files

Learners Support Publicationswww.lsp4you.com

Updating A File : Random AccessUpdating A File : Random Access

To find the total number of objects in a file using To find the total number of objects in a file using object_lengthobject_length

int n = file_size / object_length;int n = file_size / object_length;

The file size can be obtained using the function tellg( ) or The file size can be obtained using the function tellg( ) or tellp( ) when the pointer is located at the end of the file.tellp( ) when the pointer is located at the end of the file.

continue …

Page 25: Working with Files

Learners Support Publicationswww.lsp4you.com

Error Handling During File OperationsError Handling During File Operations

A file which we are attempting to open for reading does A file which we are attempting to open for reading does not exist.not exist.

The file name used for a new file may already exist.The file name used for a new file may already exist. We may attempt an invalid operation such as reading We may attempt an invalid operation such as reading

past the end-of-file.past the end-of-file. There may not be any space in the disk for storing more There may not be any space in the disk for storing more

data.data. We may use an invalid file name.We may use an invalid file name. We may attempt to perform an operation when the file is We may attempt to perform an operation when the file is

not opened for that purpose.not opened for that purpose.

Page 26: Working with Files

Learners Support Publicationswww.lsp4you.com

Error Handling During File OperationsError Handling During File Operations

The C++ file stream inherits a “stream_state” member The C++ file stream inherits a “stream_state” member from the class ios.from the class ios.

This member records information on the status of a file This member records information on the status of a file that is being currently used.that is being currently used.

The class ios supports several member functions that The class ios supports several member functions that can be used to read the status recorded in a file stream.can be used to read the status recorded in a file stream.

eof( )eof( ) fail( )fail( ) bad( )bad( ) good( ), etc.good( ), etc.

continue …

Page 27: Working with Files

Learners Support Publicationswww.lsp4you.com

Command – Line ArgumentsCommand – Line Arguments

C++ supports a feature that facilitates the supply of C++ supports a feature that facilitates the supply of argument to the main( ) function.argument to the main( ) function.

These arguments are supplied at the time of invoking the These arguments are supplied at the time of invoking the program.program.

They are typically used to pass the names of data files.They are typically used to pass the names of data files. Eg:- exam data resultEg:- exam data result

The command-line arguments are typed by the user and The command-line arguments are typed by the user and are delimited by a space.are delimited by a space.

Page 28: Working with Files

Learners Support Publicationswww.lsp4you.com

Command – Line ArgumentsCommand – Line Arguments

The main function can take two arguments.The main function can take two arguments.

main( int argc, char * argv [ ] )main( int argc, char * argv [ ] )

The first argument argc (argument counter) represents The first argument argc (argument counter) represents the number of arguments in the command line.the number of arguments in the command line.

The second argument argv (argument vector) is an array The second argument argv (argument vector) is an array of char type pointers that points to the command line of char type pointers that points to the command line arguments.arguments.

The size of the array will be equal to the value of argc.The size of the array will be equal to the value of argc.

continue …

Page 29: Working with Files

Learners Support Publicationswww.lsp4you.com

Command – Line ArgumentsCommand – Line Arguments

C:\> exam data resultsC:\> exam data results The value of argc would be 3 and argv would be an array The value of argc would be 3 and argv would be an array

of three pointers to strings as:of three pointers to strings as: argv[0] argv[0] exam exam argv[1] argv[1] data data argv[2] argv[2] results results

• …………

• …………

• infile.open(argv[1]);infile.open(argv[1]);

• …………

• …………

• outfile.open(argv[2]);outfile.open(argv[2]);

• …………

continue …

Page 30: Working with Files

Learners Support Publicationswww.lsp4you.com

Thank YouThank You

Learners Support PublicationsLearners Support Publications

www.lsp4you.comwww.lsp4you.com


Recommended