Chapter 6-File in C++
Chapter 6-File in C++
Chapter 6
Input output
2
What is a File?
▶A file is a collection on information, usually stored
on a computer’s disk.
▶ Information
can be saved to files and then later
reused when it is needed.
File opening:
▶ The file must be opened; if the file does not yet
exits, opening a file means creating it.
▶A file must be opened before you can read from
it or write to it.
▶ Either the ofstream or fstream object may be
used to open a file for writing.
▶ ifstream object is used to open a file for reading
purpose. 11
12
Cont…
Syntax for file opening
fstream fileName;
fileName.open("file.txt", ios::openmode
mode);
▶ The first argument specifies the name and
location of the file to be opened & the
second argument of the open member
function defines the mode in which the file
should be opened.
▶ Information is then saved(write) to the file,
read from the file, or both.
13
Cont…
File1.close();
return 0;}
22
More example-append
file1.close();
23
int main(){
fstream file1;
file1.open(“test.txt”,ios::in);//reading a file
if(file1.is_open()){
string mytext;
while(getline(file1,mytext)){
cout<<mytext<<endl;
file1.close();
return 0;}
24