SlideShare a Scribd company logo
Disk File I/O in
C++
Dr. Syed Aun Irtaza
Department of Computer Science
University of Engineering and Technology
(UET) Taxila
Disk File I/O with Streams
O Working with disk files requires set of classes:
O ifstream for input,
O ofstream for output.
O fstream for both input and output
O Objects of these classes can be associated with disk
files, and we can use their member functions to read
and write to the files.
O The ifstream, ofstream, and fstream classes are
declared in the FSTREAM file.
Writing Data formatted I/O,
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
char ch = 'x';
int j = 77;
double d = 6.02;
string str1 = "Hello";
string str2 = "Testing";
ofstream outfile("data.txt", ios::out | ios::trunc); //create ofstream object
outfile << ch << j << ‘ ' << d << str1 << ‘ ' << str2;
cout << "File writtenn";
return 0;
}
Writing Data formatted I/O,
int main() {
char ch = ‘x’;
int j = 77;
double d = 6.02;
string str1 = “Hello”;
string str2 = “Testing”;
ofstream outfile(“data.txt”); //create ofstream object
outfile << ch << j << ‘ ‘ << d << str1 << ‘ ‘ << str2;
cout << “File writtenn”;
return 0;
}
If the file doesn’t exist,
it is created.
If it does exist, it is
truncated and the new
data replaces the old.
Reading Data formatted I/O,
int main() {
char ch;
int j;
double d;
string str1;
string str2;
ifstream infile(“fdata.txt”);
infile >> ch >> j >> d >> str1 >> str2;
cout << ch << endl << j << endl << d << endl
<< str1 << endl << str2 << endl;
return 0;
}
Strings with Embedded Blanks
#include <fstream>
int main() {
ofstream
outfile(“TEST.TXT”);
outfile << “Hello Dear !n”;
outfile << “We are writingn”;
outfile << “data in filesn”;
outfile << “with
embeddedn”;
outfile << “blanksn”;
return 0;
}
#include <iostream>
#include<fstream>
int main() {
const int MAX = 80;
char buffer[MAX];
ifstream infile(“TEST.TXT”);
while( !infile.eof() ) {
infile.getline(buffer, MAX);
cout << buffer << endl;
}
return 0;
}
Character I/O
#include <fstream>
#include <iostream>
#include <string>
int main() {
string str = “Time is a great teacher, but
unfortunately it
kills all its pupils. Berlioz”;
ofstream outfile(“TEST.TXT”);
for(int j=0; j<str.size(); j++)
outfile.put( str[j] );
cout << “File writtenn”;
return 0;
}
Character I/O
#include <fstream>
#include <iostream>
void main() {
char ch;
ifstream infile(“TEST.TXT”);
while( infile ){
infile.get(ch); //read character
cout << ch; //display it
}
cout << endl;
}
read until EOF or error
Binary I/O
O We can write a few numbers to disk using
formatted I/O, but if you’re storing a large
amount of numerical data it’s more
efficient to use binary I/O
O In binary I/O numbers are stored as they
are in the computer’s RAM memory,
rather than as strings of characters
Binary I/O
O In binary I/O an int is stored in 4 bytes,
whereas its text version might be “12345”,
requiring 5 bytes.
O Similarly, a float is always stored in 4
bytes, while its formatted version might be
“6.02314e13”, requiring 10 bytes.
Reading & Writing an Object to Disk
struct student{
int rno;
char name[25];
};
void getdata(student &s1){
cout<<"nEnter name";cin>>s1.name;
cout<<"nEnter Roll no";cin>>s1.rno;
}
void showdata(student &s2){
cout<<"nName";cout<<s2.name;
cout<<"nRoll no"<<s2.rno;
}
Reading & Writing an Object to Disk
int main() {
student std[3];
for(int i=0; i<=2; i++)
getdata(std[i]);
ofstream outfile("std.txt", ios::binary);
for(int a=0; a<=2; a++)
outfile.write(reinterpret_cast<char*>(&std[a]), sizeof(std[a]));
ifstream infile("std.txt", ios::binary);
for(int a=0; a<=2; a++){
infile.read( reinterpret_cast<char*>(&std[a]), sizeof(std[a]));
showdata(std[a]);
}
}
The Mode Bits
File pointer positions
O Each file object has associated with it two integer values
called the get pointer and the put pointer.
O These are also called the current get position and the current
put position.
O These values specify the byte number in the file where
writing or reading will take place.
O The seekg() and tellg() functions allow you to set and
examine the get pointer.
O The seekp() and tellp() functions perform these same
actions on the put pointer.
File pointer positions
O For example, will set the put pointer to 10 bytes
before the end of the file.
O seekp(-10, ios::end);
O For example, will set the put pointer to the end of
file.
O infile.seekg(0, ios::end);
File pointer positions

More Related Content

Similar to File Handling in C++ full ppt slide presentation.ppt

ONLINE STUDENT MANAGEMENT SYSTEM
ONLINE STUDENT MANAGEMENT SYSTEMONLINE STUDENT MANAGEMENT SYSTEM
ONLINE STUDENT MANAGEMENT SYSTEMRohit malav
 
#include iostream #include cstring #include vector #i.pdf
 #include iostream #include cstring #include vector #i.pdf #include iostream #include cstring #include vector #i.pdf
#include iostream #include cstring #include vector #i.pdfanandatalapatra
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with filesramya marichamy
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with fileskirupasuchi1996
 
File handling complete programs in c++
File handling complete programs in c++File handling complete programs in c++
File handling complete programs in c++zain ul hassan
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...ssuserd6b1fd
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxRutujaTandalwade
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
Computer science project work
Computer science project workComputer science project work
Computer science project workrahulchamp2345
 

Similar to File Handling in C++ full ppt slide presentation.ppt (20)

working with files
working with filesworking with files
working with files
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
ONLINE STUDENT MANAGEMENT SYSTEM
ONLINE STUDENT MANAGEMENT SYSTEMONLINE STUDENT MANAGEMENT SYSTEM
ONLINE STUDENT MANAGEMENT SYSTEM
 
Vcs28
Vcs28Vcs28
Vcs28
 
#include iostream #include cstring #include vector #i.pdf
 #include iostream #include cstring #include vector #i.pdf #include iostream #include cstring #include vector #i.pdf
#include iostream #include cstring #include vector #i.pdf
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
Managing console i/o operation,working with files
Managing console i/o operation,working with filesManaging console i/o operation,working with files
Managing console i/o operation,working with files
 
Managing,working with files
Managing,working with filesManaging,working with files
Managing,working with files
 
File handling complete programs in c++
File handling complete programs in c++File handling complete programs in c++
File handling complete programs in c++
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 5 of 5 by...
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C
CC
C
 
PPS Notes Unit 5.pdf
PPS Notes Unit 5.pdfPPS Notes Unit 5.pdf
PPS Notes Unit 5.pdf
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Computer science project work
Computer science project workComputer science project work
Computer science project work
 

Recently uploaded

size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticspragatimahajan3
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxCapitolTechU
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesRased Khan
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsCol Mukteshwar Prasad
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptxmansk2
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfQucHHunhnh
 
How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17Celine George
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resourcesdimpy50
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxakshayaramakrishnan21
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPCeline George
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointELaRue0
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...Nguyen Thanh Tu Collection
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfbu07226
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxjmorse8
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online PresentationGDSCYCCE
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resourcesaileywriter
 

Recently uploaded (20)

size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptxslides CapTechTalks Webinar May 2024 Alexander Perry.pptx
slides CapTechTalks Webinar May 2024 Alexander Perry.pptx
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17How to the fix Attribute Error in odoo 17
How to the fix Attribute Error in odoo 17
 
Benefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational ResourcesBenefits and Challenges of Using Open Educational Resources
Benefits and Challenges of Using Open Educational Resources
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
The Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational ResourcesThe Benefits and Challenges of Open Educational Resources
The Benefits and Challenges of Open Educational Resources
 

File Handling in C++ full ppt slide presentation.ppt

  • 1. Disk File I/O in C++ Dr. Syed Aun Irtaza Department of Computer Science University of Engineering and Technology (UET) Taxila
  • 2. Disk File I/O with Streams O Working with disk files requires set of classes: O ifstream for input, O ofstream for output. O fstream for both input and output O Objects of these classes can be associated with disk files, and we can use their member functions to read and write to the files. O The ifstream, ofstream, and fstream classes are declared in the FSTREAM file.
  • 3. Writing Data formatted I/O, #include<iostream> #include<fstream> #include<string.h> using namespace std; int main() { char ch = 'x'; int j = 77; double d = 6.02; string str1 = "Hello"; string str2 = "Testing"; ofstream outfile("data.txt", ios::out | ios::trunc); //create ofstream object outfile << ch << j << ‘ ' << d << str1 << ‘ ' << str2; cout << "File writtenn"; return 0; }
  • 4. Writing Data formatted I/O, int main() { char ch = ‘x’; int j = 77; double d = 6.02; string str1 = “Hello”; string str2 = “Testing”; ofstream outfile(“data.txt”); //create ofstream object outfile << ch << j << ‘ ‘ << d << str1 << ‘ ‘ << str2; cout << “File writtenn”; return 0; } If the file doesn’t exist, it is created. If it does exist, it is truncated and the new data replaces the old.
  • 5. Reading Data formatted I/O, int main() { char ch; int j; double d; string str1; string str2; ifstream infile(“fdata.txt”); infile >> ch >> j >> d >> str1 >> str2; cout << ch << endl << j << endl << d << endl << str1 << endl << str2 << endl; return 0; }
  • 6. Strings with Embedded Blanks #include <fstream> int main() { ofstream outfile(“TEST.TXT”); outfile << “Hello Dear !n”; outfile << “We are writingn”; outfile << “data in filesn”; outfile << “with embeddedn”; outfile << “blanksn”; return 0; } #include <iostream> #include<fstream> int main() { const int MAX = 80; char buffer[MAX]; ifstream infile(“TEST.TXT”); while( !infile.eof() ) { infile.getline(buffer, MAX); cout << buffer << endl; } return 0; }
  • 7. Character I/O #include <fstream> #include <iostream> #include <string> int main() { string str = “Time is a great teacher, but unfortunately it kills all its pupils. Berlioz”; ofstream outfile(“TEST.TXT”); for(int j=0; j<str.size(); j++) outfile.put( str[j] ); cout << “File writtenn”; return 0; }
  • 8. Character I/O #include <fstream> #include <iostream> void main() { char ch; ifstream infile(“TEST.TXT”); while( infile ){ infile.get(ch); //read character cout << ch; //display it } cout << endl; } read until EOF or error
  • 9. Binary I/O O We can write a few numbers to disk using formatted I/O, but if you’re storing a large amount of numerical data it’s more efficient to use binary I/O O In binary I/O numbers are stored as they are in the computer’s RAM memory, rather than as strings of characters
  • 10. Binary I/O O In binary I/O an int is stored in 4 bytes, whereas its text version might be “12345”, requiring 5 bytes. O Similarly, a float is always stored in 4 bytes, while its formatted version might be “6.02314e13”, requiring 10 bytes.
  • 11. Reading & Writing an Object to Disk struct student{ int rno; char name[25]; }; void getdata(student &s1){ cout<<"nEnter name";cin>>s1.name; cout<<"nEnter Roll no";cin>>s1.rno; } void showdata(student &s2){ cout<<"nName";cout<<s2.name; cout<<"nRoll no"<<s2.rno; }
  • 12. Reading & Writing an Object to Disk int main() { student std[3]; for(int i=0; i<=2; i++) getdata(std[i]); ofstream outfile("std.txt", ios::binary); for(int a=0; a<=2; a++) outfile.write(reinterpret_cast<char*>(&std[a]), sizeof(std[a])); ifstream infile("std.txt", ios::binary); for(int a=0; a<=2; a++){ infile.read( reinterpret_cast<char*>(&std[a]), sizeof(std[a])); showdata(std[a]); } }
  • 14. File pointer positions O Each file object has associated with it two integer values called the get pointer and the put pointer. O These are also called the current get position and the current put position. O These values specify the byte number in the file where writing or reading will take place. O The seekg() and tellg() functions allow you to set and examine the get pointer. O The seekp() and tellp() functions perform these same actions on the put pointer.
  • 15. File pointer positions O For example, will set the put pointer to 10 bytes before the end of the file. O seekp(-10, ios::end); O For example, will set the put pointer to the end of file. O infile.seekg(0, ios::end);