File handling basics
This presentation is the property of its rightful owner.
Sponsored Links
1 / 75

File handling Basics PowerPoint PPT Presentation


  • 95 Views
  • Uploaded on
  • Presentation posted in: General

File handling Basics. Lecture 7. Stream Classes. A stream is a general name given to a flow of data. In C++ a stream is represented by an object of a particular class. So far we’ve used the cin and cout stream objects.

Download Presentation

File handling Basics

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


File handling basics

File handling Basics

Lecture 7


Stream classes

Stream Classes

  • A stream is a general name given to a flow of data.

  • In C++ a stream is represented by an object of a particular class.

  • So far we’ve used the cin and cout stream objects.

  • Different streams are used to represent different kinds of data flow.

  • For example, the ifstream class represents data flow from input disk files.


What is a file

What is a File?

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


File names

File Names

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

  • e.g;

  • Abc.txt

  • Abc.cpp

  • Abc.exe

  • Abc.html

  • Abc.bat

  • Abc.dat


The process of using a file

The Process of Using a File

  • Using a file in a program is a simple three-step process

    • The file must be opened. If the file does not yet exits, opening it means creating it.

    • Information is then saved to the file, read from the file, or both.

    • When the program is finished using the file, the file must be closed.


Figure 1

Figure 1


Figure 2

Figure 2


Writing data

Writing Data

#include <fstream>

#include <iostream>

#include <string>

using namespace std;

int main()

{

char ch = ‘a’;

int j = 100;

double d = 26.12;

string str1 = “BS”;

string str2 = “CS”;

ofstreamoutfile(“c:\\fdata.txt”);


File handling basics

outfile << ch

<< j

<< “ ”

<< d

<< str1

<< ‘ ‘

<< str2;

cout << “File written\n”;

return 0;

}


Reading data

Reading Data

#include <fstream>

#include <iostream>

#include <string>

using namespace std;

int main()

{

char ch;

int j;

double d;

string str1;

string str2;

ifstreaminfile(“fdata.txt”);


File handling basics

infile >> ch >> j >> d >> str1 >> str2;

cout << ch << endl

<< j << endl

<< d << endl

<< str1 << endl

<< str2 << endl;

return 0;

OUTPUT:

a

100

26.12

BS

CS


Setting up a program for file input output

Setting Up a Program for File Input/Output

  • Before file I/O can be performed, a C++ program must be set up properly.

  • File access requires the inclusion of fstream.h


Opening a file

Opening a File

  • Before data can be written to or read from a file, the file must be opened.

    ifstreaminputFile;

    inputFile.open(“customer.dat”);


Program

Program

// This program demonstrates the declaration of an fstream

// object and the opening of a file.

#include <iostream.h>

#include <fstream.h>

#include <string.h>

void main(void)

{

fstream dataFile; // Declare file stream object

char fileName[20];

cout << "Enter the name of a file you wish to open\n";

cout << "or create: ";

cin.getline(fileName, 20);

dataFile.open(fileName, ios::out);

cout << "The file " << fileName << " was opened.\n";

}


Program output with example input

Program Output with Example Input

Enter the name of a file you wish to open

or create: mystuff.dat [Enter]

The file mystuff.dat was opened.


Table

Table


The ios class

The iosClass

  • The ios class is the grandfather of all the stream classes, and contains the majority of the features those need to operate C++ streams.


Table of ios features

Table of ios features


Opening a file at declaration

Opening a File at Declaration

fstreamdataFile(“names.dat”, ios::in | ios::out | ios::app);

  • we use ios::app because we want to preserve whatever was in the file before and whatever we write to the file will be added following the existing contents

  • We use ios::in and ios::out because we want to perform both input and output on the file.

  • we use ios::binary because we’re writing binary objects.

  • The vertical bars between the flags cause the bits representing these flags to be logically combined into a single integer, so that several flags can apply simultaneously.


Program1

Program

// This program demonstrates the opening of a file at the

// time the file stream object is declared.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream dataFile(“c:\\mcs2\\names.dat", ios::out);

cout << "The file names.dat is open.\n";

}


Program2

Program

// This program demonstrates the close function.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream dataFile;

dataFile.open("testfile.txt", ios::out);

if (!dataFile)

{

cout << "File open error!" << endl;

return;

}

Else

{

cout << "File was created successfully.\n";

cout << "Now closing the file.\n";

dataFile.close();

}

}


Using to write information to a file

Using << to Write Information to a File

  • The stream insertion operator (<<) may be used to write information to a file.

    dataFile<< “Mansoor hates C++ programming !”


Program3

Program

// This program uses the << operator to write information to a file.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream dataFile;

dataFile.open(“c:\\bcs2\\demofile.txt", ios::out | ios::app);

if (!dataFile)

{

cout << "File open error!" << endl;

}


Program continues

Program continues

cout << "File opened successfully.\n";

cout << "Now writing information to the file.\n";

dataFile<< “Ali\n";

dataFile << “Jamal\n";

dataFile << “Kamran\n";

dataFile << “Jawad\n";

dataFile.close();

cout << "Done.\n";

}


Program screen output

Program Screen Output

File opened successfully.

Now writing information to the file.

Done.

Output to File demofile.txt

Ali

Jamal

kamran

jawad


Program4

Program

// This program writes information to a file, closes the file,

// then reopens it and appends more information.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream dataFile;

dataFile.open("demofile.txt", ios::out);

dataFile << “Ali\n";

dataFile << “Jamal\n";

dataFile.close();

dataFile.open("demofile.txt", ios::app);

dataFile << “Kamran\n";

dataFile << “Jawad\n";

dataFile.close();

}


Output to file demofile txt

Output to File demofile.txt

Ali

Jamal

kamran

Jawad


Program5

Program

#include <iostream.h>

#include <fstream.h>

#include <iomanip.h>

void main(void)

{fstream outFile("table.txt", ios::out);

int nums[3][3] = { 2897, 5, 837,

34, 7, 1623,

390, 3456, 12 };

// Write the three rows of numbers

for (int row = 0; row < 3; row++)

{

for (int col = 0; col < 3; col++)

{

outFile << setw(4) << nums[row][col] << " ";

}

outFile << endl;

}

outFile.close();

}


Contents of file table txt

Contents of File TABLE.TXT

2897 5 837

34 7 1623

390 3456 12


Using to read information from a file

Using >> to Read Information from a File

  • The stream extraction operator (>>) may be used to read information from a file.


Program6

Program

// This program uses the >> operator to read information from a file.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream dataFile;

char name[81];

dataFile.open("demofile.txt", ios::in);

if (!dataFile)

{

cout << "File open error!" << endl;

return;

}

cout << "File opened successfully.\n";

cout << "Now reading information from the file.\n\n";


Program continues1

Program continues

for (int count = 0; count < 4; count++)

{

dataFile >> name;

cout << name << endl;

}

dataFile.close();

cout << "\nDone.\n";

}


Program screen output1

Program Screen Output

File opened successfully.

Now reading information from the file.

Ali

Jamal

Kamran

Jawad

Done.


Detecting the end of a file

Detecting the End of a File

  • The eof() member function reports when the end of a file has been encountered.

    if (inFile.eof())

    inFile.close();


Program7

Program

// This program uses the file stream object's eof() member

// function to detect the end of the file.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream dataFile;

char name[81];

dataFile.open("demofile.txt", ios::in);

if (!dataFile)

{

cout << "File open error!" << endl;

return;

}

cout << "File opened successfully.\n";

cout << "Now reading information from the file.\n\n";


Program continues2

Program continues

dataFile >> name; // Read first name from the file

while (!dataFile.eof())

{

cout << name << endl;

dataFile >> name;

}

dataFile.close();

cout << "\nDone.\n";

}


Program screen output2

Program Screen Output

File opened successfully.

Now reading information from the file.

Ali

jamal

kamran

jawad

Done.


Passing file stream objects to functions

Passing File Stream Objects to Functions

  • File stream objects may be passed by reference to functions.

    boolopenFileIn(fstream &file, char name[51])

    {

    bool status;

    file.open(name, ios::in);

    if (file.fail())

    status = false;

    else

    status = true;

    return status;

    }


More detailed error testing

More Detailed Error Testing

  • All stream objects have error state bits that indicate the condition of the stream.


Table1

Table


Table2

Table


Program8

Program

// This program demonstrates the return value of the stream

// object error testing member functions.

#include <iostream.h>

#include <fstream.h>

// Function prototype

void showState(fstream &);

void main(void)

{

fstream datafile("stuff.dat", ios::out);

if (dataFile.fail())

{

cout << "cannot open the file.\n";

}


Program continues3

Program continues

int num = 10;

cout << "Writing to the file.\n";

testFile << num;// Write the integer to testFile

showState(testFile);

testFile.close();// Close the file

testFile.open("stuff.dat", ios::in);// Open for input

if (testFile.fail())

{

cout << "cannot open the file.\n";

return;

}


Program continues4

Program continues

cout << "Reading from the file.\n";

testFile >> num;// Read the only number in the file

showState(testFile);

cout << "Forcing a bad read operation.\n";

testFile >> num;// Force an invalid read operation

showState(testFile);

testFile.close();// Close the file

}

// Definition of function ShowState. This function uses

// an fstream reference as its parameter. The return values of

// the eof(), fail(), bad(), and good() member functions are

// displayed. The clear() function is called before the function

// returns.


Program continues5

Program continues

void showState(fstream &file)

{

cout << "File Status:\n";

cout << " eof bit: " << file.eof() << endl;

cout << " fail bit: " << file.fail() << endl;

cout << " bad bit: " << file.bad() << endl;

cout << " good bit: " << file.good() << endl;

file.clear();// Clear any bad bits

}


Program output

Program Output

Writing to the file.

File Status:

eof bit: 0

fail bit: 0

bad bit: 0

good bit: 1

Reading from the file.

File Status:

eof bit: 0

fail bit: 0

bad bit: 0

good bit: 1

Forcing a bad read operation.

File Status:

eof bit: 1

fail bit: 2

bad bit: 0

good bit: 0


Member functions for reading and writing files

Member Functions for Reading and Writing Files

  • File stream objects have member functions for more specialized file reading and writing.


Program9

Program

// This program uses the file stream object's eof() member

// function to detect the end of the file.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream nameFile;

char input[81];

nameFile.open(“student.txt", ios::in);

if (!nameFile)

{

cout << "File open error!" << endl;

return;

}


Program continued

Program (continued)

nameFile >> input;

while (!nameFile.eof())

{cout << input;

nameFile >> input;

}

nameFile.close();

}


The getline member function

The getline Member Function

  • dataFile.getline(str, 81, ‘$’);

    str – This is the name of a character array, or a pointer to a section of memory. The information read from the file will be stored here.

    81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read.

    ‘\n’ ‘$’– This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left our, ‘\n’ is the default.)


Program10

Program

// This program uses the file stream object's getline member

// function to read a line of information from the file.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream nameFile;

char input[81];

nameFile.open(“student.txt", ios::out);

namefile<<“Welcome”;

if (!nameFile)

{

cout << "File open error!" << endl;

return;

}


Program continues6

Program continues

Namefile.close();

Namefile.open(“student.txt”,ios::in)

nameFile.getline(input, 81); // use \n as a delimiter

while (!nameFile.eof())

{

cout << input << endl;

nameFile.getline(input, 81,’$’); // use \n as a delimiter

}

nameFile.close();

}


Program screen output3

Program Screen Output

Ch Ali

sargodha

Pakistan, 25000


Program11

Program

// This file shows the getline function with a user-

// specified delimiter.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream dataFile("names2.txt", ios::in);

char input[81];dataFile.getline(input, 81, '$');

while (!dataFile.eof())

{

cout << input << endl;

dataFile.getline(input, 81, '$');

}

dataFile.close();

}


Program output1

Program Output

Ch Ali

City Sargodha

Pakistan, 25000

Mubashir

Islamabad

Pakistan, 25000

Bilal Ahmad

PO Box 803

Sialkot, 25777


The get member function

The get Member Function

inFile.get(ch);


Program12

Program

// This program asks the user for a file name. The file is opened and its contents are //displayed on the screen.

#include <iostream.h>

#include <fstream.h>

void main(void)

{

fstream file;

char ch, fileName[51];

cout<<"Enter a file name: ";

cin>>fileName;

file.open(fileName, ios::in);

if (!file)

{

cout << fileName << “could not be opened.\n";

}


Program continues7

Program continues

file.get(ch); // Get a character

while (!file.eof())

{

cout << ch;

file.get(ch); // Get another character

}

file.close();

}


The put member function

The put Member Function

  • outFile.put(ch);


Program13

Program

// This program demonstrates the put member function.

#include <iostream.h>

#include <fstream.h>

void main(void)

{fstream dataFile("sentence.txt", ios::out);

char ch;

cout << "Type a sentence and be sure to end it with a ";

cout << "period.\n";

while (1)

{

cin.get(ch);

dataFile.put(ch);

if (ch == '.')

break;

}

dataFile.close();

}


Binary input output

Binary input/output

  • In Binary input/output, data or records are stored into files in binary format.

  • e.g in binary format, each integer takes two bytes.

  • Suppose the integer 24521 take only two bytes.

  • Binary format stores large amount of data in files on disk


Opening files in binary mode

Opening Files in Binary Mode

  • The ios::binary parameter is used to specify the binary mode.

  • e.g.

  • ofstream rec(“employee.dat”,ios:: binary);

  • Binary data is read using “read” and “write” member functions.

  • Binary data is read using an object of ifstream,ofstream (or fstream) class.


Read write function

Read/Write Function

  • object.write((char*) &rec, sizeof(rec));

  • In which

  • object:

    • represents the created object of ofstream(or fstream).

  • write

    • Member function of created object.

  • char*

    • Represent the data address of fixed length in bytes of the character type data.


File handling basics

  • rec

    • It represents a variable or object that contains data. It may be of any data type. The & address is added with it.

  • sizeof(rec)

    • Returns the size of the variable or object. The size of object is calculated first in bytes and then the data is stored.


Writing reading objects into files

Writing & reading objects into Files

  • The objects of a class can also be written into the file on the disk and read back from the file.

  • The objects are written & read in binary format with the “write” member function.

  • Same as they are read from the file with the “read” member function.

  • During objects writing on disk into file only contents of data members are stored in the form of blocks of bytes.


File handling basics

  • Same as when these blocks read from the hard disk to computer memory.


E g program to store records of employees on the disk in the form of objects

e.g; program to store records of employees on the disk in the form of objects.

#include<iostream.h>

#include<stdlib.h>

#include<fstream.h>

using namespace std;

Class employee{

private:

Char code[5], name[20],address[30];

int pay;


File handling basics

public:

Void input(void)

{

cout<<“Enter Code”;

cin>>code;

cout<<“Enter Name”;

cin>>name;

cout<<“Enter Address”;

cin>>address;

cout<<“Enter pay”;

cin>>pay;

}

};


File handling basics

int main(intargc, char *argv[])

{

employee rec;

char op;

ofstreamaddrec(“employee.dat”, ios::binary);

If(!addrec){

cout<<“File opening error”<<endl;

exit(1);

}


File handling basics

Do

{

rec.input();

addrec.write((char*)&rec,sizeof(rec));

cout<<“More Records y/n=?”;

cin>>op;}

while(op==‘y’ || op==‘Y’);

}

addrec.close();

}


A program to read back records of employees from the disk in the form of objects

A program to read back records of employees from the disk in the form of objects

#include<iostream.h>

#include<stdlib.h>

#include<fstream.h>

#include<iomanip.h>

using namespace std;

class employee{

private:

char code[5]; name[20],address[35];

int pay;


File handling basics

Public:

Void show(test2 records)

{

Cout<<setw(5)<<code<<setw(5)<<name<<setw(20)<<address<<setw(5)<<pay<<endl;

}

};


File handling basics

int main(intargc, char *argv[])

{

employee objrec;

ifstream reading(“employee.dat”,ios::binary);

if(!reading)

{

cerr<<“File opening error”<<endl;

exit(1);

}

While(reading)

{

reading.read((char*)&objrec,sizeof(objrec));

objrec.show(rec);

}

reading.close():

system("PAUSE");

return EXIT_SUCCESS;

}


  • Login