Friday, April 14, 2017

File Handling: Reading and Writing into a binary text file

Code:

#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
using namespace std;

int main()
{
    int max = 10;
    int a[max];
 
    ofstream myfile("Writing_Reading.txt",ios::binary);        //opening the file in binary mode
 
    for(int j=0;j<max;j++)                                     //assigning values(array)
            a[j] = (j + 1);
         
                                                       //writing in the file
    myfile.write(reinterpret_cast<char *>(a),sizeof(a));
    cout<<"File written."<<endl<<endl;
 
    myfile.close();                                   //closing the file
 
    ifstream my("Writing_Reading.txt",ios::binary);        //opening the file in binary mode
 
                                                      //Emptying the array
    for(int j=0;j<max;j++)
            a[j] = 0;
                                                      //Reading from the file
    my.read(reinterpret_cast<char *>(a),sizeof(a));
 
    for(int j=0;j<max;j++)                             //display array
            cout<<a[j];
 
    cout<<endl<<"Press any key to exit.";
    getch();
    return 0;
}

Output:

File Handling: Writing into a binary text file

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact