C++ | Introduction to files – Part 2

Introduction

This is a tutorial for working with files in c++. The program is given below that takes character from file and checks if it is same as it its given by user and changes the character if different. The program is extendable. Go enjoy the program. Lets begin…………

Program for files in c++.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
//clear the screen
clrscr();
//declare the charcter
char ch;
//take the input
cout<<"Enter A Character:";
cin>>ch;
//declare fstream object.
fstream file;
//open the file
file.open("Data.txt",ios::out | ios::in);
//get the character from the file
char ch2;
file.get(ch2);
//add a if-else statement.
if(ch2!=ch)
{
   file.seekp(0);
   file.put(ch);
   cout<<"The new Character is saved in Data.txt file.";
}
else
cout<<"The file contains the same character";
//get character
getch();
}

Output

Enter A Character:b
The new Character is saved in Data.txt file.

NOTE:- You will find the character you have entered is saved in Data.txt file that is mostly found BIN folder.

How does it work.

  1. You enter a character.
  2. The character is taken from file.
  3. If it is not same as it is entered by user then it puts the new character in the file.
  4. Else it prints the message that the character is same.

Extending it.

You can extend it by using name in place of character and save the name in file. This is the basic concept of c++ and can be used in any program. GO extend it….

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ and ‘fstream.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare the variable as charname the as you want.)
  5. Add cin to enter the character.(as shown in program)
  6. Declare the fstream object.
  7. Call the open.
  8. Add a if-else statement.
  9. Call the seekp(0) and put() function if not same.
  10. Cout the message to tell the user what is done.

At the end

You learnt creating the C++ program for saving a char in files. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: