Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

DATE: 12-DEC-23 STUDENT ID: S23BME007

LAB#12
FILING
1) (a) Write a C++ program to create a new text file and write some text into it and also open this
existing text file and display its contents on the console.
SOURCE CODE:
//WRITING IN FILE
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream myFile;
myFile.open("oopbme.txt",ios::out);//creating file
if(!myFile){
cout<<"File doesnot exist";
}
else{
cout<<"File created successfully "<<endl;
}
myFile<<" Testing file :) "<<endl;
myFile<<"Hello !! here are some example text given "<<endl;
myFile<<"We are sitting in Biocomputing And Simulation
Lab"<<endl;
cout<<"Text written in the file successfully !! "<<endl;
myFile.close();
}
// READING A FILE
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream myFile;
myFile.open("oopbme.txt",ios::in);//creating file
if(!myFile){
cout<<"File doesnot exist";
}
else{

}
string d;
while(getline(myFile, d)){
cout<<d<<endl;
}
myFile.close();
}

OUTPUT:
File created successfully
Text written in the file successfully !!

--------------------------------
Testing file :)
Hello !! here are some example text given
We are sitting in Biocomputing And Simulation Lab

--------------------------------
(2) Write a C++ program to append new data to an existing text file.
SOURCE CODE:

#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream myFile;
myFile.open("oopbme.txt",ios::app);//creating file
if(!myFile){
cout<<"File doesnot exist";
}
else{
cout<<"File created successfully "<<endl;
}
myFile<<" Testing file :) "<<endl;
myFile<<"Hello !! here are some example text given "<<endl;
myFile<<"We are sitting in Biocomputing And Simulation
Lab"<<endl;
cout<<"Text written in the file Appended successfully !! "<<endl;

myFile.close();
}

OUTPUT:

File created successfully


Text written in the file Appended successfully !!

--------------------------------

CONCLUSION:
Data is permanently stored on a storage device using files. File handling offers a way to save
program output in a file and manipulate it in different ways. C++ file handling stores program output
and performs operations on it, permanently storing data on a storage device. An abstraction that
symbolizes a device used for input and output activities is called a stream. Binary files offer multiple
file openings in a program, require less memory for data storage, and can read or write structured
data like structures and class objects.

*********************************************************************************

You might also like