Chapter 14-File IO
Chapter 14-File IO
Chapter 14-File IO
Programming II
Chapter 14: File IO (Input/Output) in C++
Program
1
Outline
▪ File Operations
▪ Read data from file
▪ Examples
write
Program
read
3
File IO
❑ What?
▪ iostream library provides cin and cout methods for reading from keyboard
and writing/displaying on screen
#include <iostream>
#include <fstream>
2:45pm
4
File IO
❑ Opening a file
open(filename)
▪ To read or write file, we have to open a file first.
▪ We can use either ofstream or fstream open(filename, mode)
fstream file;
file.open(“filename.dat”, ios::in)
5
File IO
❑ Closing a file
fstream file;
file.open(“filename.dat”, ios::out)
…………………..
//read/write code here
…………………..
file.close( );
6
File IO
❑ Writing data to a file
▪ We can use ofstream or fstream ofstream file;
for creating file variable file.open(“MyFile.dat”);
▪ Then use << to write data
▪ file<<data1<<data2<<endl;
fstream file;
file.open(“MyFile.data”, ios::out);
Functions for write data to file
Function Description fstream file;
file<<word; Write one data in word to file string filename=“MyFile.dat”;
file<<word1<<“\t” Write two data (word1 and word2) //file.open(filename, ios::out); //error
<<word2; separated by a tab to file
file.open(filename.c_str( ), ios::out);
Remark: You can write data to file just similar way you
display data using cout 7
Writing data to a file #include <fstream>
#include <iostream>
#include <fstream> using namespace std;
❑ Example
#include <iostream>
using namespace std; int main () {
string data; //char data[100];
int main () { // open a file in write mode.
string data; fstream file;
// open a file in write mode. file.open("filename.txt", ios::out);
ofstream file; //file.open("filename.txt", ios::app); //append
file.open("filename.txt");
//file.open(“filename.txt", ios::app); //append cout<<"Writing data to the file"<< endl;
cout<<"Enter your name: ";
cout<<"Writing data to the file"<< endl; ciin>>data;
cout<<"Enter your name: "; file<<data<<endl;
cin>>data;
file<<data<<endl; cout<<"Enter your age: ";
cin>>data;
cout<<"Enter your age: "; file<<data<<endl;
cin>>data;
file<<data<<endl; file.close();
}
file.close();
}
8
File IO
❑ Reading from a file
▪ We can use ifstream or fstream ifstream file;
for creating file variable file.open(“filename.dat”);
file.close(); file.close();
} }
} } 10
File IO
❑ Examples
11
Q&A
12
Practice
❑ Exercise
1. Write a program to read data from a file below. Store those data in an array
of structure. Then add one more info of a student to that array. Ask a user
for that info. Finally store all data in this array to a file having the same
name as the previously read file.
13