26
FILE HANDLING

file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

FILE HANDLINGFILE HANDLING

Page 2: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Why to use Files:

• Convenient way to deal large quantities of data.

• Store data permanently (until file is deleted).

• Avoid typing data into program • Avoid typing data into program multiple times.

• Share data between programs.

• We need to know:

• how to "connect" file to program

• how to tell the program to read data

Page 3: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

The fstream.h header file

�Streams act as an interface between files andprograms.

�They represent as a sequence of bytes and deals withthe flow of data.

�Every stream is associated with a class having memberfunctions and operations for a particular kind of datafunctions and operations for a particular kind of dataflow.

�File � Program ( Input stream) - reads

�Program � File (Output stream) – write

�All designed into fstream.h and hence needs to beincluded in all file handling programs.

�Diagrammatically as shown in next slide

Page 4: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

All rights reserved 4

Page 5: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

• ofstream: Stream class to write on files

• ifstream: Stream class to read from files

• ifstream: Stream class to read from files

• fstream: Stream class to both read and write from/to files.

Page 6: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

The Stream Class

Hierarchy

ios

istreamget()getline()

ostreamput()write()<<

fstreambase

getline()read()>>

write()<<

iostream

IfstreamOpen()Tellg()Seekg()

OfstreamOpen()Tellp()Seekp()

fstream

Page 7: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Two kinds of files: –

• Text :: contains ASCII codes only

• Binary :: can contain non-ASCII characters • Image, audio, video, executable, etc. • To check the end of executable, etc. • To check the end of file here, the file size value (also stored on disk) needs to be checked.

All rights reserved 7

Page 8: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

• Text File

– Data is stored as ASCII values

– Strings , characters and numeric data is stored as ASCII values

– Each digit occupy one byte of memory space.

– Data is organized into lines with new-line character as terminators.

– Any text editor can be used to see content of file.

– If you use the << operator to read from the file and the >> operator

to write to the file then the file will be accessed in text mode

• Binary File• Binary File

– A binary file is basically any file that is not "line-oriented"

– Exact copies of memory content are stored.

– Strings, characters and numeric data are stored as binary data(8 bit

value).

– If instead you use the put() and get() or read() and write() functions

then the file will be accessed in binary mode.

8

Page 9: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

ios::in Open for input operations.

ios::out Open for output operations.

ios::binary Open in binary mode.

ios::noreplace Error while opening if the file exist, opening it

unless ate or app mode is set.

ios::nocreate If the file does not exist, opening it with the

open() function gets impossible.

Set the initial position at the end of the file.

ios::ate

Set the initial position at the end of the file.If this flag is not set, the initial position is the beginning of the file.Pointer can be moved anywhere in the file.

ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file.

ios::trunc

If the file is opened for output operations and it already existed, its previous content is deleted before opening the file.

Page 10: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Open a file

• open (filename, mode);

Where filename is a string representing the name of the file to be opened, and mode is an optional parameter with the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

ofstream myfile; myfile.open ("example.txt");

Page 11: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

1) ofstream file;

file.open (“test.bin", ios::out | ios::app | ios::binary);| ios::binary);

2) ofstream file (“test.bin", ios::out | ios::app | ios::binary);

Page 12: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

// basic file operations#include <iostream>#include <fstream>using namespace std; int main () { { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; }

Page 13: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Close a file• When we are finished with our input and output

operations on a file we shall close it so that the operating system is notified and its resources become available again. This member function flushes the associated buffers and closes the file:

file.close();

• Once this member function is called, the object can • Once this member function is called, the object can be re-used to open another file, and the file is available again to be opened by other processes.

• In case that an object is destroyed while still associated with an open file, the destructor automatically calls the member function close.

Page 14: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main ()

{

string line;

ifstream myfile ("example.txt");

if (myfile.is_open())

{

while ( getline (myfile,line) ) while ( getline (myfile,line) )

{

cout << line << '\n';

}

myfile.close();

} else

cout << "Unable to open file";

return 0;

}

Page 15: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

#include <fstream>

#include <iostream>

using namespace std;

int main ()

{ char data[100];

// open a file in write mode.

ofstream outfile;

outfile.open("afile.dat");

cout << "Writing to the file" << endl;

cout << "Enter your name: ";

cin.getline(data, 100);

// write inputted data into the file.

outfile << data << endl;

cout << "Enter your age: ";

cin >> data;

cin.ignore(); cin.ignore();

// again write inputted data into the file.

outfile << data << endl;

// close the opened file. outfile.close();

// open a file in read mode.

ifstream infile;

infile.open("afile.dat");

cout << "Reading from the file" << endl;

infile >> data; // write the data at the screen.

cout << data << endl;

// again read the data from the file and display it.

infile >> data;

cout << data << endl;

// close the opened file.

infile.close();

return 0; }

Page 16: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Checking state flags

The following member functions exist to check for specific states of a stream

(all of them return a bool value):

1) bad():- Returns true if a reading or writing operation fails. For example, in

the case that we try to write to a file that is not open for writing or if the

device where we try to write has no space left.

2) fail():- Returns true in the same cases as bad(), but also in the case that a

format error happens, like when an alphabetical character is extracted when

we are trying to read an integer number.we are trying to read an integer number.

3) eof():- Returns true if a file open for reading has reached the end.

4) good():- It is the most generic state flag: it returns false in the same cases in

which calling any of the previous functions would return true. Note

that good and bad are not exact opposites (good checks more state flags at

once).

The member function clear() can be used to reset the state flags.

Page 17: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Stream state member functions• In C++, file stream classes inherit a stream state

member from the ios class, which gives out the

information regarding the status of the stream.

• For e.g.:

––eofeof() () ––used to check the end of file characterused to check the end of file character

––fail()fail()-- used to check the status of file at used to check the status of file at ––fail()fail()-- used to check the status of file at used to check the status of file at

opening for I/Oopening for I/O

––bad()bad()-- used to check whether invalid file used to check whether invalid file

operations or unrecoverable error .operations or unrecoverable error .

––good()good()-- used to check whether the previous file used to check whether the previous file

operation has been successfuloperation has been successful

Page 18: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

• app comes from 'append'- all output will be added (appended) to the end of the file. In other words you cannot write anywhere else in the file but at the end

• ate come form 'at end' - it sets the stream position at the end of the file stream position at the end of the file when you open it but you are free to move it around (seek) and write wherever it pleases you.

All rights reserved 18

Page 19: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Stream state member functionsStream state member functions

••In C++, file stream classes inherit a stream state In C++, file stream classes inherit a stream state

member from the member from the iosios class, which gives out the class, which gives out the

information regarding the status of the stream.information regarding the status of the stream.

For e.g.:For e.g.:

––eofeof() () ––used to check the end of file characterused to check the end of file character––eofeof() () ––used to check the end of file characterused to check the end of file character

––fail()fail()-- used to check the status of file at opening used to check the status of file at opening for I/Ofor I/O

––bad()bad()-- used to check whether invalid file used to check whether invalid file operations or unrecoverable error .operations or unrecoverable error .

––good()good()-- used to check whether the previous file used to check whether the previous file operation has been successfuloperation has been successful

Page 20: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

Reading /Writing from/to Textual FilesReading /Writing from/to Textual Files

• To write:– put() – writing single

character

– << operator – writing an object

• To read:– get() – reading a

#include <fstream.h>main(){

// Writing to fileofstream OutFile("my_file.txt");OutFile<<"Hello "<<5<<endl;OutFile.close();

int number;– get() – reading a

single character of a buffer

– getline() – reading a single line

– >> operator –reading a object

int number;char dummy[15];

// Reading from fileifstream InFile("my_file.txt");InFile>>dummy>>number;

InFile.seekg(0);InFile.getline(dummy,sizeof(dummy));InFile.close();

}

Page 21: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

1: To access file handling routines:

#include <#include <fstream.hfstream.h>>

2: To declare variables that can be used to access file:

ifstreamifstream in_streamin_stream;;

ofstreamofstream out_streamout_stream;;

3: To connect your program's variable (its internal name)

to an external file (i.e., on the Unix file system):to an external file (i.e., on the Unix file system):

in_stream.openin_stream.open("infile.dat");("infile.dat");

out_stream.openout_stream.open("outfile.dat");("outfile.dat");

4: To see if the file opened successfully:

if (if (in_stream.failin_stream.fail())())

{ { coutcout << "Input file open failed<< "Input file open failed\\n";n";

exit(1);exit(1); // requires <// requires <stdlib.hstdlib.h>}>}

Page 22: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

• The following member functions exist to check for specific

states of a stream (all of them return a bool value):

• bad() Returns true if a reading or writing operation fails. For

example, in the case that we try to write to a file that is not

open for writing or if the device where we try to write has no

space left.

• fail() Returns true in the same cases as bad(), but also in the

case that a format error happens, like when an alphabetical

character is extracted when we are trying to read an integer

number.

• eof() Returns true if a file open for reading has reached the end.

• good() It is the most generic state flag: it returns false in the

same cases in which calling any of the previous functions

would return true. Note that good and bad are not exact

opposites (good checks more state flags at once).

The member function clear() can be used to reset the state

flags. All rights reserved 22

Page 23: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

• All i/o streams objects keep internally -at least- one internal

position:

ifstream, like istream, keeps an internal get position with the

location of the element to be read in the next input operation.

ofstream, like ostream, keeps an internal put position with the

location where the next element has to be written.location where the next element has to be written.

Finally, fstream, keeps both, the get and the put position,

like iostream.

These internal stream positions point to the locations within

the stream where the next reading or writing operation is

performed. These positions can be observed and modified

using the following member functions:

Page 24: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

• get – read a single character from text file and

store in a buffer. e.g file.get(ch);

• put - writing a single character in textfile e.g.

file.put(ch); file.put(ch);

• getline - read a line of text from text file store

in a buffer. e.g file.getline(s,80);

• We can also use file>>ch for reading and

file<> operator does not accept white spaces.

Page 25: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

ios::in Open for input operations.

get(ch) Extract one character into ch

get(str) Extract characters into array str

get(str,MAX) Extract upto max characters into array str

get(str,DELIM)Extract into array str upto specified delim ((typically

uptil \n). Leave delimiting character in stream.

get(str,MAX,DELIM)Extract into array str untill MAX or delim (typically uptil

\n). Leave delimiting character in stream.

getline(str,MAX,DELIM)Extract into array str untill MAX or delim (typically uptil

\n). Extract delimiting character

Page 26: file handling own [Read-Only]included in all file handling programs. ... • Text File – Data is stored as ASCII values – Strings , characters and numeric data is stored as ASCII

• write() and read() function

write() and read() functions write and read

blocks of binary data.

example:example:

file.read((char *)&obj, sizeof(obj));

file.write((char *)&obj, sizeof(obj));