SlideShare ist ein Scribd-Unternehmen logo
1 von 43
File Operations
(CS1123)
By
Dr. Muhammad Aleem,
Department of Computer Science,
Mohammad Ali Jinnah University, Islamabad
2013
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.
• All files are assigned a name that is used for
identification purposes by the operating system
and the user.
– E.g.,
MyProg.cpp, Marks.txt, etc.
Basic File Operations
• Opening a file
• Writing to a file
• Reading from a file
• Close a file
• …
Writing to File
Reading form File
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
• A stream is a general name given to a flow of data.
• 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 represents data
flow from input disk files.
File I/O (files are attached to streams)
• 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>
Opening a File
• Before data can be written to, or read from a
file, before that the file must be opened.
ifstream inputFile;
inputFile.open(“customer.txt”);
Open function opens a file if
it exist previously, otherwise
it will create that file (in the
current directory)
Example (File opening)
#include <iostream.h>
#include <fstream.h>
void main()
{
fstream dataFile; //Declare file stream object
char fileName[81];
cout<<"Enter name of file to open or create”;
cin.getline(fileName, 81);
dataFile.open(fileName, ios::out );
cout << "The file “<<fileName<<" was opened.";
}
File modes
Default File Opening Modes
File Types Default Open Modes
ofstream
File is opened for output only. (Information may be
written to 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.
ifstream
The file is opened for input only. (Information may
be read from the file, but not written to it.) File’s
contents will be read from its beginning.
If the file does not exist, the open function fails.
File Mode
Flag
Meaning
ios::app
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::binary
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::noreplace
If the file does not already exist, this flag will cause
the open function to fail. (The file will not be
created.)
File Mode
Flag
Meaning
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.
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::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 be deleted
(truncated). This is the default mode used by
ios::out.
Opening a File at Declaration
fstream dataFile(“names.dat”, ios::in | ios::out);
#include <iostream.h>
#include <fstream.h>
void main( )
{
fstream dataFile("names.txt", ios::in | ios::out);
cout << "The file names.txt was opened.n";
}
Testing for Open Errors
fstream dataFile;
dataFile.open(“cust.dat”, ios::in);
if (!dataFile)
{
cout << “Error opening file.n”;
}
Another way to Test for Open Errors
fstream dataFile;
dataFile.open(“cust.dat”, ios::in);
if (dataFile.fail())
{
cout << “Error opening file.n”;
}
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 successfullyn";
cout << "Now closing the filen";
dataFile.close();
}
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
Example – File writing using <<
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
dataFile.open("demofile.txt", ios::out);
if (!dataFile)
{
cout << "File open error!" << endl;
return;
}
cout << "File opened successfully.n";
cout << "Now writing information to the file.n";
dataFile << "Jonesn";
dataFile << "Smithn";
dataFile << "Willisn";
dataFile << "Davisn";
dataFile.close();
cout << "Done.n";
}
Program Screen Output
File opened successfully.
Now writing information to the file.
Done.
Output to File demofile.txt
Jones
Smith
Willis
Davis
File Storage in demofile.txt
Example – Append
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
dataFile.open("demofile.txt", ios::out);
dataFile << "Jonesn";
dataFile << "Smithn";
dataFile.close();
dataFile.open("demofile.txt", ios::app);
dataFile << "Willisn";
dataFile << "Davisn";
dataFile.close();
}
Jones
Smith
Willis
Davis
Example – Append (Output)
File Output Formatting
• File output may be formatted the same way as
screen output.
File Output Formatting - Example
#include <iostream.h>
#include <fstream.h>
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;
dataFile.precision(5);
dataFile << num << endl;
dataFile.precision(4);
dataFile << num << endl;
dataFile.precision(3);
dataFile << num << endl;
}
123.456
123.45600
123.4560
123.456
File Output Formatting Example -Output
Using >> to Read Information from a File
• The stream extraction operator (>>) may be
used to read information from a file.
#include <iostream.h>
#include < fstream.h>
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.nn";
for (int count = 0; count < 4; count++)
{
dataFile >> name;
cout << name << endl;
}
dataFile.close();
cout << "nDone.n"; }
Using >> to Read Information from a File
File opened successfully.
Now reading information from the file.
Jones
Smith
Willis
Davis
Done.
Using >> to Read Information from a File (output)
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();
#include <iostream.h>
#include <fstream.h>
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.nn";
dataFile >> name; // Read first name from the file
while (!dataFile.eof())
{
cout << name << endl;
dataFile >> name;
}
dataFile.close();
cout << "nDone.n";
}
Detecting the End of a File
File opened successfully.
Now reading information from the file.
Jones
Smith
Willis
Davis
Done.
Detecting the End of a File - Output
Note on eof()
• In C++, “end of file” doesn’t mean the program is
at the last piece of information in the file, but
beyond it.
• The eof() function returns true when there is
no more information to be read.
Lecture: 16/12/13
getline Member Function
• dataFile.getline(str, 81, ‘n’);
str – Name of a character array. Information read
from 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. This argument is optional If
it’s left out, ‘n’ is the default.)
Example Program
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream nameFile;
char input[81];
nameFile.open(“Address.txt", ios::in);
if (!nameFile)
{
cout << "File open error!" << endl;
return;
}
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 Output
Mohammad Ai Jinnah University
Islamabad Expressway, Zone V, Kahuta Road
Islamabad Pakistan
Program Example
// 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 Output
Jayne Murphy
47 Jones Circle
Almond, NC 28702
Bobbie Smith
217 Halifax Drive
Canton, NC 28716
Bill Hammet
PO Box 121
Springfield, NC 28357
Character IO
The get Member Function
inFile.get(ch);
//one character at a time
Example 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";
return;
}
file.get(ch); // Get a character
while (!file.eof())
{
cout << ch;
file.get(ch); // Get another character
}
file.close();
}
The put Member Function
outFile.put(ch);
//Writes or outputs one character at a
time to the file
Example 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();
}

Weitere ähnliche Inhalte

Was ist angesagt?

Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 

Was ist angesagt? (20)

File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
File handling in c
File handling in cFile handling in c
File handling in c
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
File Handling in C
File Handling in C File Handling in C
File Handling in C
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
File handling
File handlingFile handling
File handling
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
file
filefile
file
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Java File I/O
Java File I/OJava File I/O
Java File I/O
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 

Ähnlich wie Cs1123 10 file operations

csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
HEMAHEMS5
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
Teguh Nugraha
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 

Ähnlich wie Cs1123 10 file operations (20)

Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
File management in C++
File management in C++File management in C++
File management in C++
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Data file handling
Data file handlingData file handling
Data file handling
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
working with files
working with filesworking with files
working with files
 
File operations
File operationsFile operations
File operations
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handling
 
Aray in Programming
Aray in ProgrammingAray in Programming
Aray in Programming
 
Data file operations in C++ Base
Data file operations in C++ BaseData file operations in C++ Base
Data file operations in C++ Base
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 

Mehr von TAlha MAlik

Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
TAlha MAlik
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
TAlha MAlik
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
TAlha MAlik
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
TAlha MAlik
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
TAlha MAlik
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_prog
TAlha MAlik
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
TAlha MAlik
 

Mehr von TAlha MAlik (11)

Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Cs1123 7 arrays
Cs1123 7 arraysCs1123 7 arrays
Cs1123 7 arrays
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_prog
 
Cs1123 1 intro
Cs1123 1 introCs1123 1 intro
Cs1123 1 intro
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 

Cs1123 10 file operations

  • 1. File Operations (CS1123) By Dr. Muhammad Aleem, Department of Computer Science, Mohammad Ali Jinnah University, Islamabad 2013
  • 2. 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. • All files are assigned a name that is used for identification purposes by the operating system and the user. – E.g., MyProg.cpp, Marks.txt, etc.
  • 3. Basic File Operations • Opening a file • Writing to a file • Reading from a file • Close a file • …
  • 6. 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 • A stream is a general name given to a flow of data. • 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 represents data flow from input disk files.
  • 7. File I/O (files are attached to streams) • 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>
  • 8. Opening a File • Before data can be written to, or read from a file, before that the file must be opened. ifstream inputFile; inputFile.open(“customer.txt”); Open function opens a file if it exist previously, otherwise it will create that file (in the current directory)
  • 9. Example (File opening) #include <iostream.h> #include <fstream.h> void main() { fstream dataFile; //Declare file stream object char fileName[81]; cout<<"Enter name of file to open or create”; cin.getline(fileName, 81); dataFile.open(fileName, ios::out ); cout << "The file “<<fileName<<" was opened."; } File modes
  • 10. Default File Opening Modes File Types Default Open Modes ofstream File is opened for output only. (Information may be written to 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. ifstream The file is opened for input only. (Information may be read from the file, but not written to it.) File’s contents will be read from its beginning. If the file does not exist, the open function fails.
  • 11. File Mode Flag Meaning ios::app 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::binary 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::noreplace If the file does not already exist, this flag will cause the open function to fail. (The file will not be created.)
  • 12. File Mode Flag Meaning 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. 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::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 be deleted (truncated). This is the default mode used by ios::out.
  • 13. Opening a File at Declaration fstream dataFile(“names.dat”, ios::in | ios::out); #include <iostream.h> #include <fstream.h> void main( ) { fstream dataFile("names.txt", ios::in | ios::out); cout << "The file names.txt was opened.n"; }
  • 14. Testing for Open Errors fstream dataFile; dataFile.open(“cust.dat”, ios::in); if (!dataFile) { cout << “Error opening file.n”; }
  • 15. Another way to Test for Open Errors fstream dataFile; dataFile.open(“cust.dat”, ios::in); if (dataFile.fail()) { cout << “Error opening file.n”; }
  • 16. 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 successfullyn"; cout << "Now closing the filen"; dataFile.close(); }
  • 17. 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
  • 18. Example – File writing using << #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; dataFile.open("demofile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.n"; cout << "Now writing information to the file.n"; dataFile << "Jonesn"; dataFile << "Smithn"; dataFile << "Willisn"; dataFile << "Davisn"; dataFile.close(); cout << "Done.n"; }
  • 19. Program Screen Output File opened successfully. Now writing information to the file. Done. Output to File demofile.txt Jones Smith Willis Davis
  • 20. File Storage in demofile.txt
  • 21. Example – Append #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; dataFile.open("demofile.txt", ios::out); dataFile << "Jonesn"; dataFile << "Smithn"; dataFile.close(); dataFile.open("demofile.txt", ios::app); dataFile << "Willisn"; dataFile << "Davisn"; dataFile.close(); }
  • 23. File Output Formatting • File output may be formatted the same way as screen output.
  • 24. File Output Formatting - Example #include <iostream.h> #include <fstream.h> 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; dataFile.precision(5); dataFile << num << endl; dataFile.precision(4); dataFile << num << endl; dataFile.precision(3); dataFile << num << endl; }
  • 26. Using >> to Read Information from a File • The stream extraction operator (>>) may be used to read information from a file.
  • 27. #include <iostream.h> #include < fstream.h> 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.nn"; for (int count = 0; count < 4; count++) { dataFile >> name; cout << name << endl; } dataFile.close(); cout << "nDone.n"; } Using >> to Read Information from a File
  • 28. File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done. Using >> to Read Information from a File (output)
  • 29. 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();
  • 30. #include <iostream.h> #include <fstream.h> 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.nn"; dataFile >> name; // Read first name from the file while (!dataFile.eof()) { cout << name << endl; dataFile >> name; } dataFile.close(); cout << "nDone.n"; } Detecting the End of a File
  • 31. File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done. Detecting the End of a File - Output
  • 32. Note on eof() • In C++, “end of file” doesn’t mean the program is at the last piece of information in the file, but beyond it. • The eof() function returns true when there is no more information to be read.
  • 34. getline Member Function • dataFile.getline(str, 81, ‘n’); str – Name of a character array. Information read from 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. This argument is optional If it’s left out, ‘n’ is the default.)
  • 35. Example Program #include <iostream.h> #include <fstream.h> void main(void) { fstream nameFile; char input[81]; nameFile.open(“Address.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; } 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(); }
  • 36. Program Screen Output Mohammad Ai Jinnah University Islamabad Expressway, Zone V, Kahuta Road Islamabad Pakistan
  • 37. Program Example // 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(); }
  • 38. Program Output Jayne Murphy 47 Jones Circle Almond, NC 28702 Bobbie Smith 217 Halifax Drive Canton, NC 28716 Bill Hammet PO Box 121 Springfield, NC 28357
  • 40. The get Member Function inFile.get(ch); //one character at a time
  • 41. Example 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"; return; } file.get(ch); // Get a character while (!file.eof()) { cout << ch; file.get(ch); // Get another character } file.close(); }
  • 42. The put Member Function outFile.put(ch); //Writes or outputs one character at a time to the file
  • 43. Example 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(); }