C++ examples for File Stream:stream
Using seekp( ) and seekg( ) to reverse characters in a file.
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main(int argc, char *argv[]) { long n, i, j;/* ww w . java 2 s . co m*/ char ch1, ch2; // Open the file for binary input and output operations. fstream finout("main.cpp", ios::in | ios::out | ios::binary); if(!finout) { cout << "Cannot open input file.\n"; return 1; } n = 2; // Use random access to reverse the characters. for(i=0, j=n; i < j; ++i, --j) { // First, get the two characters. finout.seekg(i, ios::beg); finout.get(ch1); finout.seekg(j, ios::beg); finout.get(ch2); // Now, write them to the opposite locations. finout.seekp(i, ios::beg); finout.put(ch2); finout.seekp(j, ios::beg); finout.put(ch1); // Confirm the success of each read/write cycle. if(!finout.good()) { cout << "Error reading or writing characters."; finout.clear(); break; } } finout.close(); // Confirm that no errors occurred when closing the file. if(!finout.good()) { cout << "A file error occurred."; return 1; } return 0; }