C++ | Introduction to files – Part 1

Join Programming and Development Chat Groups on Uphub.io

Introduction

This is a tutorial for files in c++. The program takes a character from the user and saves it in a file. The program is extendable. Go enjoy the program. Lets begin……

Program for file 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);
//put the character in the file
file.put(ch);
//print a message.
cout<<"The Character is saved in Data.txt file.";
//get character
getch();
}

Output
Enter A Character:a
The 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 saved in file.

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 and put function.
  8. Cout the message to tell the user that the char is saved.

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: