Files in C++
Example 1: C++ program to create a file
/*In this program we create a file and check whether file is created successfully or not and then close the file.*/
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream file;
[Link]("[Link]", ios::out);
if(!file)
cout<<"Error in creating file"<<endl;
else
cout<<"File created successfully"<<endl;
[Link]();
return 0;
}
Example 2: C++ program to write text to a file
/*In this program, we will create a file and then write some text into that file*/
#include<iostream>
#include<fstream>
using namespace std;
int main(){
fstream file;
[Link]("[Link]", ios::out);
if(!file){
cout<<"Error in creating file"<<endl;
}
else{
cout<<"File created successfully"<<endl;
file<<"Welcome to Files in C++"<<endl;//writing to a file
cout<<"Something has been written to your file, go check it"<<endl;
}
[Link]();
return 0;
}
Example 3: C++ program to read text from a file
/*In this program, we will create a file, write some text into that file, then read the text from that file*/
#include<iostream>
#include<fstream>
using namespace std;
int main(){
char ch;
fstream file;
[Link]("[Link]", ios::out| ios::in);
if(!file){
cout<<"Error in creating file"<<endl;
}
else{
cout<<"File created successfully"<<endl;
file<<"Welcome to Files in C++"<<endl;//writing to a file
[Link]();
}
[Link]("[Link]");
while(![Link]()){
file >> noskipws >> ch; //reading from file
cout << ch; //printing
}
[Link]();
return 0;
}
Example 4: //C++ program to write and read values using variables in/from file.
//C++ program to write and read values using variables in/from file.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char name[30], surname[30], programme[30];
int age;
fstream file;
[Link]("[Link]", ios::out);
if(!file){
cout<<"Error in creating file.."<<endl;
}
else{
cout<<"\n File created successfully."<<endl;
cout<<"Enter your name: ";
[Link](name,30);
cout<<"Enter your surname: ";
[Link](surname,30);
cout<<"Enter your programme: ";
[Link](programme,30);
cout<<"Enter age: ";
cin>>age;
//write into file
file<<name<<" "<<surname<<" "<<programme<<" "<<age<<endl;
[Link]();
cout<<"\n File saved and closed successfully."<<endl;
}
//Open file in input mode and read data
[Link]("[Link]",ios::in);
if(!file){
cout<<"Error in opening file..";
return 0;
}
file>>name;
file>>surname;
file>>programme;
file>>age;
cout<<"NAME: "<<name<<" ,SURNAME: "<<surname<<" ,PROGRAMME: "<<programme<<" ,AGE: "<<age;
return 0;
}