×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to write and read values using variables in/from file

In this program, we will write and read variable's values in/from text file. Here you will learn how to write values in file and how to access them.

Write and read variable's values in the 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];
    int age;
    fstream file;
 
    file.open("aaa.txt",ios::out);
    if(!file)
    {
      cout<<"Error in creating file.."<<endl;
      return 0;
    }
    cout<<"\nFile created successfully."<<endl;
 
    //read values from kb
    cout<<"Enter your name: ";
    cin.getline(name,30);
    cout<<"Enter age: ";
    cin>>age;
    //write into file
    file<<name<<" "<<age<<endl;
 
    file.close();
    cout<<"\nFile saved and closed succesfully."<<endl;
 
    //re open file in input mode and read data
    //open file
    file.open("aaa.txt",ios::in);
    if(!file){
        cout<<"Error in opening file..";
        return 0;
    }
    file>>name;
    file>>age;
 
    cout<<"Name: "<<name<<",Age:"<<age<<endl;
    return 0;
}

Output

    File created successfully.
    Enter your name: Mike
    Enter age: 21

    File saved and closed succesfully.
    Name: Mike,Age:21 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.