C based file I/O, copy a file, substituting spaces for tabs in the process. - C++ File Stream

C++ examples for File Stream:File Operation

Description

C based file I/O, copy a file, substituting spaces for tabs in the process.

Demo Code

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
   FILE *in, *out;//  w  w  w. j a va2 s . c  o m
   int tabsize = 3;
   int tabcount;
   char ch;
   int completion_status = 0;
   if(argc != 3) {
      cout << "usage: detab <in> <out>\n";
      return 1;
   }
   if((in = fopen(argv[1], "rb"))==NULL) {
      cout << "Cannot open input file.\n";
      return 1;
   }
   if((out = fopen(argv[2], "wb"))==NULL) {
      cout << "Cannot open output file.\n";
      fclose(in);
      return 1;
   }
   tabcount = 0;
   do {
      // Read a character from the input file.
      ch = fgetc(in);
      if(ferror(in)) {
         cout << "Error reading input file.\n";
         completion_status = 1;
         break;
      }
      // If tab found, output appropriate number of spaces.
      if(ch == '\t') {
         for(int i=tabcount; i < tabsize; ++i) {
            // Write spaces to the output file.
            fputc(' ', out);
         }
         tabcount = 0;
      }
      else {
         // Write the character to the output file.
         fputc(ch, out);
         ++tabcount;
         if(tabcount == tabsize) tabcount = 0;
         if(ch == '\n' || ch == '\r') tabcount = 0;
      }
      if(ferror(out)) {
         cout << "Error writing to output file.\n";
         completion_status = 1;
         break;
      }
   } while(!feof(in));
   fclose(in);
   fclose(out);
   if(ferror(in) || ferror(out)) {
      cout << "Error closing a file.\n";
      completion_status = 1;
   }
   return completion_status;
}

Result


Related Tutorials