KEMBAR78
Lecture 5 File Handling Part 1 | PDF | Computer File | Input/Output
0% found this document useful (0 votes)
27 views29 pages

Lecture 5 File Handling Part 1

The document provides an overview of file handling in C++, including the differences between files and variables, the use of streams for file input/output, and various file operations such as opening, reading, writing, and closing files. It also explains different opening modes and error handling when working with files. Examples are provided to illustrate how to implement file operations in C++.

Uploaded by

mushreenmajid86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views29 pages

Lecture 5 File Handling Part 1

The document provides an overview of file handling in C++, including the differences between files and variables, the use of streams for file input/output, and various file operations such as opening, reading, writing, and closing files. It also explains different opening modes and error handling when working with files. Examples are provided to illustrate how to implement file operations in C++.

Uploaded by

mushreenmajid86
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

File Handling

FILES

• A file is a collection of 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

2
FILES VS VARIABLES

• Files can hold huge amounts of data


 E.g. Text file containing personal information etc.
• Ordinary variables are kept in main memory which is
temporary and have limited size
 E.g. int x, string name etc.

3
C++ STREAMS

• A Stream is a general name given to flow of data


• e.g. cin>> and cout<< Data
PROGRAM

Input
Output
Stream
Stream
>>
DEVICES OR <<
FILES
Data
istream class ostream class

4
C++ STREAMS CONT..

• For files we use,


 ifstream – input from the file
 ofstream – output to the file
 fstream -input and output to the file

• To use these objects, you should include header file,


<fstream.h>

5
FILE OPERATIONS

• Opening a file
• Writing to a file
• Reading from a file
• Close a file…

6
WRITE OPERATION

• Writing data into a file

7
READ OPERATION

• Reading data from a file

8
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

9
SETTING UP A PROGRAM FOR FILE INPUT /
OUTPUT
• Before data can be written to or read from a file, the file must be
opened
ifstream inputFile; Declare file stream object

inputFile.open(“customer.dat”);

Open function opens a file if it exist previously, otherwise it will


create that file (in the current directory)

10
EXAMPLE
void main(void)
{
fstream dataFile; // Declare file stream object
char fileName[81];
cout << "Enter the name of a file you wish to open\
n";
cout << "or create: ";
cin.getline(fileName, 81);
dataFile.open(fileName, ios::out);
cout << "The file " << fileName << " was opened.\n";
}

11
EXAMPLE

12
OPENING MODES

File Type Default Open Mode


ofstream 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).
ifstream 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.

13
OPENING MODES CONT..
File Mode Meaning
Flag
ios::ap p Append mode. If the file already exists, its contents are preserved
and all output is written to the end of the file. By default, this
flag causes the file to be created if it does not exist.
ios::ate If the file already exists, the program goes directly to the end of
it. Output may be written anywhere in the file.
ios::b in ary Binary mode. When a file is opened in binary mode, information is
written to or read from it in pure binary format. (The default mode
is text.)
ios::in Input mode. Information will be read from the file. If the file does
not exist, it will not be created and the open function will fail.

14
OPENING MODES CONT..

File Mode Meaning


Flag
ios::nocreate If the file does not already exist, this flag
will cause the open function to fail. (The file
will not be created.)
ios::noreplace If the file already exists, this flag will cause
the open function to fail. (The existing file
will not be opened.)
ios::out Output mode. Information will be written to
the file. By default, the file’s contents will be
deleted if it already exists.
ios::trunc If the file already exists, its contents will be15
OPENING A FILE AT DECLARATION

• fstream dataFile(“names.dat”, ios::in | ios::out);

• E.g.
#include <iostream.h>
#include <fstream.h>
void main( )
{
fstream dataFile("names.txt", ios::in | ios::out);
cout << "The file names.txt was opened.\n";
}

16
TESTING FOR ERROR

fstream dataFile;
dataFile.open(“rwu.dat”, ios::in);
if (!dataFile)
{
cout << “Error opening file.\n”;
}

17
TESTING FOR ERROR CONT..
• Another way of testing an error during opening a file

fstream dataFile;
dataFile.open(“rwu.dat”, ios::in);
if (dataFile.fail())
{
cout << “Error opening file.\n”;
}

18
CLOSING A FILE
• A file should be closed when a program is finished using it.

void main(void)
{
fstream dataFile;
dataFile.open("testfile.txt", ios::out);
if (!dataFile)
{
cout << "File open error!”<<endl;
return;
}
cout << "File was created successfully\n";
cout << "Now closing the file\n";
dataFile.close();
}
19
USING << TO WRITE INFORMATION TO A
FILE
• The stream insertion operator (<<) may be used to write
information to a file.

outputFile<<“I love C++ programming !”;

fstream Object

20
USING << TO WRITE INFORMATION TO A FILE
CONT..
void main(void){
fstream dataFile;
dataFile.open("demofile.txt", ios::out); Output
if (!dataFile) { File opened
cout << "File open error!" << endl; successfully.
return; } Now writing
cout << "File opened successfully.\n"; information to the
file.
cout << "Now writing information to the file.\n";
dataFile << "Jones\n"; Done.
dataFile << "Smith\n";
dataFile << "Willis\n"; Output to File
dataFile << "Davis\n"; demofile.txt
dataFile.close(); Jones
cout << "Done.\n"; Smith
} Willis
Davis
21
USING << TO WRITE INFORMATION TO A FILE
CONT..
void main(void){ Output
fstream dataFile;
dataFile.open("demofile.txt", ios::out);
if (!dataFile) {
cout << "File open error!" << endl;
return; }
cout << "File opened successfully.\n";
Outputinformation
cout << "Now writing to File to the file.\n";
dataFile << "Jones\n";
dataFile << "Smith\n";
dataFile << "Willis\n";
dataFile << "Davis\n";
dataFile.close();
cout << "Done.\n";
}

22
FILE OUTPUT FORMATTING CONT..
• File output may be formatted the same way as screen output
void main(void){
fstream dataFile;
float num = 123.456;
dataFile.open("numfile.txt", ios::out);
if (!dataFile){cout << "File open error!" << endl;
return;
}
dataFile << num << endl; Output
dataFile.precision(5);
dataFile << num << endl;
123.456
dataFile.precision(4); 123.45600
dataFile << num << endl; 123.4560
dataFile.precision(3);
dataFile << num << endl; 123.456
}
23
USING >> TO READ INFORMATION FROM A
FILE
void main(void){
fstream dataFile;
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";
for (int count = 0; count < 4; count++){
File opened successfully.
//char name[20]; Now reading information from the file.
string name;
dataFile >> name; Jones
cout << name << endl; Smith
} Willis
dataFile.close(); Davis
cout << "\nDone.\n"; }
Done. 24
USING >> TO READ INFORMATION FROM A
FILE

25
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();

26
DETECTING THE END OF A FILE CONT..
void main(void){
fstream dataFile;
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";
string name;
dataFile >> name; // Read first name from the file
while (!dataFile.eof()){ File opened successfully.
cout << name << endl; Now reading information from the file.
dataFile >> name;} Jones
dataFile.close(); Smith
cout << "\nDone.\n";} Willis
Davis
Done. 27
DETECTING THE END OF A FILE CONT..

28
EXAMPLE
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream nameFile;
char input[81]; File open error!
nameFile.open("Address.txt", ios::in); If File Does not Exist!!!
if (!nameFile)
{
cout << "File open error!" << endl;
return 0;
}
nameFile.getline(input, 81);
while (!nameFile.eof())
{
cout << input << endl;
nameFile.getline(input, 81);
}
nameFile.close();
return 0; RWU
} 6th Rd, Satellite Town, Rawalpindi, 46300
Rawalpindi, Punjab, Pakistan
29

You might also like