Simple programs

Like most programmers, I sometimes have to return to a language I have used for a while, and it’s like I’ve never written in it before! It takes a couple of hours to get my head in the game and remember what I’m doing. So, I thought, what if I write a standard simple program, and write it in every language I know. That would be useful in the future, as a reminder.

The program should accept the name of an input file on the command line. That input file contains my name, Tim. The code must produce a new version of the file, replacing Tim with a name passed on the command line.

[tjinkers@ebl-oel6vm1 file_reader]$ cat input.txt
This file belongs to Tim. Tim owns it
and any changes must be made by Tim.
If you change it without Tim's permission
Tim will get cross.

[tjinkers@ebl-oel6vm1 file_reader]$ ./file_reader.pl -f input.txt -c Tim -n David
[tjinkers@ebl-oel6vm1 file_reader]$ cat input.txt.out
This file belongs to David. David owns it
and any changes must be made by David.
If you change it without David's permission
David will get cross.

[tjinkers@ebl-oel6vm1 file_reader]$

In Perl this looks like:

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Std;
our ($opt_f, $opt_n, $opt_c);
my ($line);
getopt('f:n:c:');
die "Please enter a file to process using -f \n" unless (defined $opt_f);
die "Please enter a new name using -n \n" unless (defined $opt_n);
die "Please enter the name to change using -c \n" unless (defined $opt_c);
die "Unable to open input file " unless (open my $infile, "", $opt_f . ".out");
while () {
    chomp;
    $line = $_;
    $line =~ s/$opt_c/$opt_n/g;
    print $oufile $line . "\n";
}
close $infile;
close $oufile;

In Python 2 we have

#!/usr/bin/python
import os
import re
from optparse import OptionParser
SUFFIX=".out"

def main () :
    global filename
    parser = OptionParser()
    parser.add_option("-f", "--file", dest="filename",
                      help="the file to update", metavar="FILE")
    parser.add_option("-n", "--name", dest="name",
                      help="the name to replace Tim with", metavar="NAME")
    parser.add_option("-c", "--fromname", dest="fromname",
                      help="the name be replaced", metavar="FROMNAME")
    (options, args) = parser.parse_args()
    if  not options.filename :
        print "You must specify the file to modify"
        exit(-1)
    if  not options.name :
        print "You must specify the name to replace Tim with"
        exit(-1)
    if  not options.fromname :
        print "You must specify the name to be replaced"
        exit(-1)
    fin = open(options.filename, 'r')
    fout = open(options.filename + SUFFIX, 'w')

    for line in fin :
        fout.write(re.sub(options.fromname, options.name, line))
    fin.close()
    fout.close()

main()

Java now – a bit more wordy!

import java.io.*;
public class filereader {
   public static void main (String[] args) {
      String p_f = null;
      String p_n = null;
      String p_c = null;
      String SUFFIX = ".out";
      int i = 0;
      while (i < args.length ) {
         // Process -f
         if ( args[i].compareTo("-f") == 0 ) {
            i++;
            if ( i < args.length ) {
                p_f=args[i];
            } else {
                System.out.println("No file name specified");
                System.exit(-1);
            }
         }
         // Process -n
         if ( args[i].compareTo("-n") == 0 ) {
            i++;
            if ( i < args.length ) {
               p_n=args[i];
            } else {
               System.out.println("No new name specified");
               System.exit(-1);
            }
         }
         // Process -c
         if ( args[i].compareTo("-c") == 0 ) {
            i++;
            if ( i < args.length ) {
               p_c=args[i];
            } else {
               System.out.println("No name to change specified");
               System.exit(-1);
            }
         }
         i++;
      }
      if ( p_f == null ) {
         System.out.println("No file name specified");
         System.exit(-1);
      }
      if ( p_n == null) {
         System.out.println("No new name specified");
         System.exit(-1);
      }
      if ( p_c == null) {
         System.out.println("No name to change specified");
         System.exit(-1);
      }
      File infile = new File(p_f);
      if ( ! infile.exists() ) {
         System.out.println("File " + p_f + " not found");
         System.exit(-1);
      }
      try {
         FileReader ifile = new FileReader(p_f);
         FileWriter ofile = new FileWriter(p_f + SUFFIX);
         BufferedReader buffer = new BufferedReader(ifile);
         BufferedWriter obuffer = new BufferedWriter(ofile);
         String line = "";
         while (( line = buffer.readLine() ) != null ){
            obuffer.write(line.replaceAll(p_c,p_n));
            obuffer.newLine();
         }
         buffer.close();
         obuffer.close();
      }
      catch ( IOException e) {
         System.out.println("A file error occured");
      }
   }
}

C++
I am no C++ programmer, a proper C++ coder will probably look at this code and laugh!

#include 
#include 
#include 
#include 
using namespace std;

int main ( int argc, char *argv[] )
{
   string filename;
   string ofilename;
   string fromname;
   string name;
   string line;

   if ( argc != 7 ) {
      printf( "usage: %s filename\n", argv[0] );
      return -1;
   }
   int i = 0;
   while ( i < argc ) {
      if ( strcmp(argv[i], "-f" ) == 0 ) {
         i++;
         if ( i < argc ) {
            filename.assign(argv[i]);
            ofilename.assign(filename + ".out");
         } else {
            cout << "No file name specified" << "\n";
            return -1;
         }
      }
      if ( strcmp(argv[i], "-n" ) == 0 ) {
         i++;
         if ( i < argc ) {
            name.assign(argv[i]);
         } else {
            cout << "No new name specified" << "\n";
            return -1;
         }
      }
      if ( strcmp(argv[i], "-c" ) == 0 ) {
         i++;
         if ( i < argc ) {
            fromname.assign(argv[i]);
         } else {
            cout << "No name to change specified" << "\n";
            return -1;
         }
      }
      i++;
   }
   if ( filename.size() == 0 ) {
      cout << "No file name specified" << "\n";
      return -1;
   }
   if ( name.size() == 0 ) {
      cout << "No new name specified" << "\n";
      return -1;
   }
   if ( fromname.size() == 0 ) {
      cout << "No name to change specified" << "\n";
      return -1;
   }
   cout << "File Name: " << filename << "\n";
   cout << "Output File Name: " <<  ofilename << "\n";
   cout << "Name: " << name << "\n";

   ifstream iptr;
   iptr.open(filename.c_str(), std::ifstream::in);
   if ( ! iptr ) {
      cout << "Unable to read " << filename << "\n";
      return -1;
   }
   ofstream optr;
   optr.open (ofilename.c_str(), std::ofstream::out);
   if ( ! optr ) {
      cout << "Unable to write to " << ofilename << "\n";
      return -1;
   }
   while ( ! iptr.eof() ) {
      getline( iptr, line);
      while ( line.find("Tim") < line.length() ) {
         line.assign(line.substr(0,line.find(fromname)) + name 
             + line.substr(line.find(fromname) + fromname.length()));
      }
      optr << line << "\n";
   }
   iptr.close();
   optr.close();
}

More languages to follow!

Advertisements

About jinkerson
Christian husband and father, rugby fan and computer programmer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: