ios::ate places the get-position pointer at the file end, enable tellg() to return the size of the file : File End EOF « File « C++






ios::ate places the get-position pointer at the file end, enable tellg() to return the size of the file

  
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;

void print_error(const char* p1, const char* p2 = 0);

int main(int argc, char* argv[])
{ 
     if (3 != argc)
        print_error("usage: function input_file output_file");

     ifstream in(argv[1], ios::binary | ios::ate);                     
     if (!in) print_error("cannot open input file", argv[1]);

     long N = in.tellg();                                              

     char buffer[N];                                                   

     in.seekg(ios::beg);                                               

     ofstream out(argv[2], ios::binary);                               
     if (!out) print_error("cannot open output file", argv[2]);

     in.read(buffer, N);                                               
     out.write(buffer, N);                                             

     if (!in.good()) {
        print_error("something strange happened");
        exit(1);
     }

     in.close();
     out.close();
     return 0;
}

void print_error(const char* p1, const char* p2) {
     if (p2) 
        cerr << p1 << ' ' << p2 << endl;
     else 
        cerr << p1 << endl;
     exit(1);
}
  
    
  








Related examples in the same category

1.Use eof() to read and display a text file.
2.While it is not the end of a file, output file line by line