Super friendly <br/>code & developer communities

Super friendly
code & developer communities

A place for coders and developers to share, learn and grow together.

C++ | Introduction to files – Part 2

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++.

void main()
//clear the screen
//declare the charcter
char ch;
//take the input
cout<<"Enter A Character:";
//declare fstream object.
fstream file;
//open the file"Data.txt",ios::out | ios::in);
//get the character from the file
char ch2;
//add a if-else statement.
   cout<<"The new Character is saved in Data.txt file.";
cout<<"The file contains the same character";
//get character


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

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….

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.

P.S. If you have any questions, click here to join our community and feel free to ask any questions.