At least two program based on file handling

Creating a file using file stream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//C++ program to create a file.
#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!!!";
       return 0;
   }
    
   cout<<"File created successfully.";
    
   //closing the file
   file.close();
    
   return 0;
}
    File created successfully.

Program to read text character by character in C++

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
	char ch;
	const char *fileName="test.txt";
	
	//declare object
	ifstream file;
	
	//open file
	file.open(fileName,ios::in);
	if(!file)
	{
		cout<<"Error in opening file!!!"<<endl;
		return -1; //return from main
	}
	
	//read and print file content
	while (!file.eof()) 
	{
		file >> noskipws >> ch;	//reading from file
		cout << ch;	//printing
	}
	//close the file
	file.close();
	
	return 0;
}
Output
Hello friends, How are you?
I hope you are fine and learning well.
Thanks.