/*write c++ program that create an output file,write information to it,close the file and open it again as an input file and read the information from the file*/
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
const int MAX=10;
int array1[MAX]={10,20,30,40,50};
int array2[MAX];
int main()
{
ofstream os;//create output stream
os.open("test.txt",ios::trunc | ios::binary);//opening file
if(!os)
{
cerr<<"could not open output file\n";//error handling
exit(1);
}
cout<<"writing the content to the file...\n\n";
os.write((char*)&array1,sizeof(array1));//writing 'array1'to file
if(!os)
{
cerr<<"could not write to file\n";//error handling
exit(1);
}
os.close();//close the file
ifstream is;//create input stream for reading the content from file
is.open("test.txt",ios::binary);
if(!is)
{
cerr<<"could not open input file\n";//error handling
exit(1);
}
cout<<"reading the content from the file....\n";
is.read((char*)&array2,sizeof(array2));//reading the content in
//another array 'array2'
if(!is)
{
cerr<<"could not read from file\n";//error handling
exit(1);
}
for(int j=0;j<MAX;j++)//check data
cout<<" "<<array2[j];
return 0;
}
/*output
[student@localhost ~]$ g++ file.cpp
[student@localhost ~]$ ./a.out
writing the content to the file...
reading the content from the file....
10 20 30 40 50 0 0 0 0 0[student@localhost ~]$ */
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
const int MAX=10;
int array1[MAX]={10,20,30,40,50};
int array2[MAX];
int main()
{
ofstream os;//create output stream
os.open("test.txt",ios::trunc | ios::binary);//opening file
if(!os)
{
cerr<<"could not open output file\n";//error handling
exit(1);
}
cout<<"writing the content to the file...\n\n";
os.write((char*)&array1,sizeof(array1));//writing 'array1'to file
if(!os)
{
cerr<<"could not write to file\n";//error handling
exit(1);
}
os.close();//close the file
ifstream is;//create input stream for reading the content from file
is.open("test.txt",ios::binary);
if(!is)
{
cerr<<"could not open input file\n";//error handling
exit(1);
}
cout<<"reading the content from the file....\n";
is.read((char*)&array2,sizeof(array2));//reading the content in
//another array 'array2'
if(!is)
{
cerr<<"could not read from file\n";//error handling
exit(1);
}
for(int j=0;j<MAX;j++)//check data
cout<<" "<<array2[j];
return 0;
}
/*output
[student@localhost ~]$ g++ file.cpp
[student@localhost ~]$ ./a.out
writing the content to the file...
reading the content from the file....
10 20 30 40 50 0 0 0 0 0[student@localhost ~]$ */
No comments:
Post a Comment