file i/o (base)

#include <iostream>
#include <fstream>  //for the file iostream
#include <cstdlib>   //for the exit(EXIT_FAILURE)
const int size=20;
int main(void)
{
 using namespace std;

 char filename[size];

 int arr[5];

 ofstream outfile;
 cout<<"enter the filename: ";
 cin.getline(filename,size);

    for (int j=0;j<5;j++)
 {  
  cout<<"please input arr["<<j<<"]:"<<endl;
  cin>>arr[j];
 }
    for (int s=0;s<5;s++)
 {
  cout<<arr[s];
 // cout<<' ';  for text
 }
   
 outfile.open(filename);
/* outfile<<arr[0]<<endl;
 outfile<<arr[1]<<endl;
 outfile<<arr[2]<<endl;
 outfile<<arr[3]<<endl;
 outfile<<arr[4]<<endl;  */

    for (int k=0;k<5;k++)
 {
  outfile<<arr[k]<<" ";
  //outfile<<" ";   for text
 } 
 
 outfile.close();

 ifstream infile;
 infile.open(filename);
 if (!infile.is_open())
 {
  cout<<"can not open the file"<<filename<<endl;
  cout<<"pro exit.\n";
  exit(EXIT_FAILURE);
 }

 double val;
 double sum=0.0;
 int count=0;

// infile>>val;
 while(infile>>val)  //(infile.good())
 {
  ++count;
  sum+=val;
//  infile>>val;
 }

 if (infile.eof())
 cout<<"end of the reached.\n";
 else if(infile.fail())
 cout<<"the miss data.\n";
 else 
 cout<<"the unknow reason\n";
 if (0==count)
    cout<<"No Data.\n";
 else
 {
  cout<<"count= "<<count<<endl;
  cout<<"sum: "<<sum<<endl;
  cout<<"Ave: "<<sum/count<<endl;
 }
 infile.close();

 return 0;
}

posted @ 2007-01-30 23:47  Edward Xie  阅读(126)  评论(0编辑  收藏  举报