Swap characters in a file with error checking. : File Utility « File « C++






Swap characters in a file with error checking.

 

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

int main(int argc, char *argv[])
{
  if(argc!=2) {
    cout << "usage: SWAP <filename>\n";
    return 1;
  }

  // open file for input/output
  fstream io(argv[1], ios::in | ios::out | ios::binary);

  if(!io) {
    cout << "Cannot open file.\n";
    return 1;
  }

  char ch1, ch2;
  long i;

  for(i = 0 ;!io.eof(); i+=2) {
    io.seekg(i, ios::beg);
    if(!io.good()) 
       return 1;
    io.get(ch1);
    if(io.eof()) 
       continue;
    io.get(ch2);
    if(!io.good()) 
       return 1;
    if(io.eof()) 
       continue;
    io.seekg(i, ios::beg);
    if(!io.good()) 
       return 1;
    io.put(ch2);
    if(!io.good()) 
       return 1;
    io.put(ch1);
    if(!io.good()) 
       return 1;
  }

  io.close();
  if(!io.good()) return 1;

  return 0;
}

           
         
  








Related examples in the same category

1.Read and display a text file line by line.
2.Display contents of specified file in both ASCII and in hex.
3.Create a file comparision utility.
4.Copy a text file and display number of chars copied.
5.Word count for input file: file read with ifstream
6.Copy files
7.Copy a file and display number of chars copied.
8.Concatenate files
9.Swap characters in a file.
10.Copy a file and reverse case of letters.
11.Count letters.
12.Copy a file and reverse case of letters with error checking.
13.Copy and convert tabs to spaces.
14.Search file.