03 File IO
03 File IO
Programming II
File IO (Input/Output) in C++
Attendance on Moodle
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 Data txt
▪ fstream library is used for writing and reading file
▪ ofstream : only for wring data to file
#include <iostream>
#include <fstream>
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
Write data to file
8
Read data from file
9
Write data from user input to file
10
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();
} }
} } 12
StudentList.txt
ID Name Age
B101 Sok 17
B102 Sao 20
B109 Dara 18
B110 Seyha 22
13
File IO
❑ Examples
14
Q&A
15
Read CSV data
Mydata.csv