/**************************************************************************** ** COPYRIGHT (C): 1996 Cay S. Horstmann. All Rights Reserved. ** PROJECT: Computing Concepts with C++ ** FILE: caesar.cpp -- modified by JGM data file: crypt_in.txt (input) ** UPDATED: RJB Tue Apr 17 15:10:41 PDT 2001 ** STATUS: Compiles clean but untested ****************************************************************************/ #include #include #include #include using namespace std; void usage(string program_name) { cout << "Usage: " << program_name << " [-d] [-kn] infile outfile\n"; exit(EXIT_FAILURE); } void open_file_error(string filename) { cout << "Error opening file " << filename << "\n"; exit(EXIT_FAILURE); } int remainder( int a, int n) { if( a >= 0) return a % n; else return n -1 - ( -a -1) %n; } char encrypt(char ch, int k) { const int NLETTER = 26; //leters in alphabet if( 'A' <= ch && ch <= 'Z') return static_cast('A' + remainder(ch -'A' + k, NLETTER)); if( 'a' <= ch && ch <= 'z') return static_cast('a' + remainder(ch -'a' + k, NLETTER)); return ch; } void encrypt_file(fstream& in, fstream& out, int k) { char ch; while( in.get(ch)) out.put(encrypt(ch, k)); } int intvalue(string s) { //p460 with a different name istrstream instr(s.c_str()); int n; instr >> n; return n; } int main(int argc, char* argv[]) { bool decrypt = false; int key = 3; int nfile = 0; /* the number of files specified */ fstream infile; fstream outfile; if (argc < 3 || argc > 5) usage(string(argv[0])); int i; for (i = 1; i < argc; i++) { string arg = string(argv[i]); if (arg.substr(0, 1) == "-") /* it is a command line option */ { string option = string(arg).substr(1, 1); if (option == "d") decrypt = true; else if (option == "k") key = intvalue(string(arg).substr(2, arg.length() - 2)); } else { nfile++; if (nfile == 1) { infile.open(arg.c_str(), ios::in); if (infile.fail()) open_file_error(arg); } else if (nfile == 2) { outfile.open(arg.c_str(), ios::out); if (outfile.fail()) open_file_error(arg); } } } if(nfile != 2) usage(string(argv[0])); if (decrypt) key = 26 - key; encrypt_file(infile, outfile, key); infile.close(); outfile.close(); return EXIT_SUCCESS; } /* SAMPLE run $more crypt_in.txt The quick brown fox jumped over the lazy dog. This input file will be encrypted. a.out -k11 crypt_in.txt crypt_out.txt $ more crypt_out.txt Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr. Estd tyafe qtwp htww mp pyncjaepo. $ a.out -d -k11 crypt_out.txt decrypt_out.txt $ more decrypt_out.txt The quick brown fox jumped over the lazy dog. This input file will be encrypted. */