C++/File/File End EOF
ios::ate places the get-position pointer at the file end, enable tellg() to return the size of the file
<source lang="cpp">
- 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);
}
</source>
Use eof() to read and display a text file.
<source lang="cpp">
- include <iostream>
- include <fstream>
using namespace std; int main(int argc, char *argv[]) {
char ch; ifstream fin("text.txt"); if(!fin) { cout << "Cannot open file.\n"; return 1; } do { fin.get(ch); if(!fin.eof() && (fin.fail() || fin.bad())) { cout << "Input Error\n"; fin.close(); return 1; } if(!fin.eof()) cout << ch; } while(!fin.eof()); fin.clear(); fin.close(); if(!fin.good()) { cout << "Error closing file."; return 1; } return 0;
}
</source>
While it is not the end of a file, output file line by line
<source lang="cpp">
- include <iostream>
- include <fstream>
using namespace std; int main () {
char buffer[256]; ifstream myfile ("test.txt"); while (! myfile.eof() ) { myfile.getline (buffer,100); cout << buffer << endl; } return 0;
}
</source>