Binary File-Write (simple program)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char name[50];
ofstream file("D://Ali.txt",ios::binary);
cout<<"Enter name :";
cin.get(name,50);
file.write((char*)&name,sizeof(name));
cout<<"File is write"<<endl;
file.close();
return 0;
}
Binary File-Read (simple program)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char name;
ifstream file("D://Ali.txt",ios::binary);
while(!file.eof() && name!='\0')
{
file.read((char*)&name,sizeof(name));
cout<<name;
}
cout<<endl;
cout<<"File is Read"<<endl;
file.close();
return 0;
}
Binary File-Write (with Structure)
#include <iostream>
#include <fstream>
using namespace std;
int const SIZE=50;
struct student
{
char name[SIZE];
int roll;
char clas[SIZE];
};
int main()
{
student std1;
ofstream file("D://Ali.txt",ios::binary);
cout<<"Enter name :";
cin>>std1.name;
cout<<"Enter Roll No :";
cin>>std1.roll;
cout<<"Enter Class :";
cin>>std1.clas;
file.write((char*)&std1,sizeof(std1));
cout<<"File is write"<<endl;
file.close();
return 0;
}
Binary File-Read (with Structure)
#include <iostream>
#include <fstream>
using namespace std;
int const SIZE=50;
struct student
{
char name[SIZE];
int roll;
char clas[SIZE];
};
int main()
{
student std1;
ifstream file("D://Ali.txt",ios::binary);
if(!file)
{
cout<<"File is not located"<<endl;
}
else
{
file.read((char*)&std1,sizeof(std1));
cout<<"Name :"<<std1.name<<"\nRoll No :"<<std1.roll<<"\nClass :"<<std1.clas<<endl;
}
file.close();
cout<<"File is Read"<<endl;
return 0;
}
Dynamic Array (Example)
#include <iostream>
using namespace std;
int main()
{
int* arr=NULL;
int size;
cout<<"How many number u want?";
cin>>size;
int sum=0;
arr=new int[size];
for(int i=0;i<size;i++)
{
cout<<"Enter number :";
cin>>arr[i];
}
for(i=0;i<size;i++)
{
sum=sum+arr[i];
}
cout<<sum;
return 0;
}