infolink

Wednesday, 28 May 2014

Write data in text file C++ Filling



To read and write data into file is called filling. Here you learn how to write data in text file.
First include fstream library.

#include <fstream>

#include <fstream>
 Then in the main function make an object of ofstream and pass the text file name with extention as a parameter to object like this:

ofstream myfile("items_file.txt");

After that open this file and write data in the file.


Example:

In this example I will create “items_file.txt”. and take a number as a input from user and store it into that text file.
Compile and run the below code and check it out.

Write data in text file C++ Filling Code
Write data in text file C++ Filling Code

 Code is here:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
      ofstream myfile("items_file.txt");
      if (myfile.is_open())
     {
            int number;
           cout<<"Enter that Number which you want to write in text file"<<endl;
           cin>>number;
           myfile << number<<"\n";
           myfile.close();
            cout<<"Record Inserted"<<endl;
     }
     else cout << "Unable to open file";
    system("PAUSE");
    return EXIT_SUCCESS;
}

No comments:

Post a Comment