lesson 3
lesson 3
▪ File Operations
▪ Read data from file
File IO (Input/Output) in C++ ▪ Write data to file
Program
“File IO refers to the transfer of data
1 either to or from a storage medium.” 2
File IO File IO
❑ What? ❑ What?
▪ “File IO refers to the transfer of data either to or from a storage ▪ iostream library provides cin and cout methods for reading from keyboard
medium.”
and writing/displaying on screen Data txt
write
▪ fstream library is used for writing and reading file
▪ ofstream : only for wring data to file
#include <iostream>
read #include <fstream>
3 4
File IO File IO
❑ Opening a file ❑ Closing a file
open(filename)
▪ To read or write file, we have to open a file first. ▪ We should close file before terminate the program file.close( );
▪ We can use either ofstream or fstream open(filename, mode)
fstream file;
Mode Description ofstream file; file.open(“filename.dat”, ios::out)
ios::app Append mode. Data is added more file.open(“filename.dat”) …………………..
ios::in Open file for reading. //read/write code here
ios::out Open file for writing. …………………..
fstream file;
If file does not exist, create a new file.
If file exists, content is overridden file.open(“filename.dat”, ios::out)
file.close( );
fstream file;
file.open(“filename.dat”, ios::in)
5 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;
Write data to file
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 8
Read data from file Write data from user input to file
9 10
file.get(ch) Read data from file one character at a time. file.close(); file.close();
getline(file, line) Read data from file one line at a time. Return } }
false when no data to read 11 } } 12
StudentList.txt
ID Name Age File IO
B101 Sok 17
B102
B109
Sao
Dara
20
18
❑ Examples
B110 Seyha 22
▪ Read and write data from/to file
13 14
Q&A Mydata.csv