CS1101C Practical Exam

Session 2 (1000 - 1145 hours)

Caesar's Cipher

The name of your C program file must be called caesar.c, files with any other name will not be marked.

Caesar's Cipher is a simple way to encrypt and decrypt strings. Your job is to implement encryption and decryption for Caesar's Cipher.

The scheme is pretty straight forward: given a message of N2 characters (pad with extra spaces if the message has less than N2 characters), put the characters into a N x N matrix row-wise (left to right, top to bottom). The encrypted message is simply the string resulted by reading the matrix column-wise (top to bottom, left to right).

For example, if the original message is:

"Programming Lab!" (16 chars i.e. 4 x 4)

Fill it into a 4 x 4 matrix (don't forget the space!):

P r o g
r a m m
i n g
L a b !

The encrypted message is: "PriLranaomgbgm !"

Work out the decryption algorithm on your own.

Assume all messages always start with a non-blank character. All trailing blanks must be removed from the original messages. Your resulting encrypted and decrypted messages must also have all trailing blanks removed. Always use the smallest square matrix possible that can contain your message. If the number of characters in your message is not a perfect square, keep padding with blanks at the end of the string until the number of characters is a square number.

Your program must do the following:

  1. Read in unencrypted text from the file plain_in.txt. The file may contain multiple lines. Each line is to be encrypted separately from other lines. Store the encrypted text into the output file cipher_out.txt line by line, overwriting the output file if it already exists.
  2. Read in encrypted text from the file cipher_in.txt. The file may contain multiple lines. Each line is to be decrypted separately from other lines. Store the decrypted text into the output file plain_out.txt line by line, overwriting the output file if it already exists.
  3. Assume each line in the input file will never exceed 100 characters, and there are no blank lines in the input file. Assume also that the input files always exist.

Sample plain_in.txt and cipher_in.txt files have been placed in your directory by the pesetup program.

We will test your program with other plain_in.txt files and other cipher_in.txt files.

All the best!

Some useful UNIX commands (in case you forgot what you did in Lab 0):

  1. "ls -l": lists all the files in the directory.
  2. "cp a.txt b.txt": copies a.txt to b.txt.
  3. "mv a.txt b.txt": moves / renames a.txt to b.txt.