Object Oriented Programming
Group B -
Practical : 4
Problem Statement : Write a C++ program that creates an output file, writes information to it, closes the file, open
it again as an input file and read the information from the file.
Check Out Code Here 👇
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
using namespace std; | |
int main() | |
{ | |
fstream file; //object of fstream class | |
//opening file "sample.txt" in out(write) mode | |
file.open("sample.txt",ios::out); | |
if(!file) | |
{ | |
cout<<"Error in creating file!!!"<<endl; | |
return 0; | |
} | |
cout<<"File created successfully."<<endl; | |
//write text into file | |
file<<"Hello World!!"; | |
//closing the file | |
file.close(); | |
//again open file in read mode | |
file.open("sample.txt",ios::in); | |
if(!file) | |
{ | |
cout<<"Error in opening file!!!"<<endl; | |
return 0; | |
} | |
//read untill end of file is not found. | |
char ch; //to read single character | |
cout<<"File content : "; | |
while(!file.eof()) | |
{ | |
file>>ch; //read single character from file | |
cout<<ch; | |
} | |
file.close(); //close file | |
return 0; | |
} |
Code can get updated so also come back later to see if there is any changes. Also if there is any problem with code you can comment below. If you like it, do share with your friends.😊
Comments
Post a Comment