#include #include #include #include int encrypt(int key, char ch) { return (ch + key) % 256; } int decrypt(int key, char ch) { return (ch - key) % 256; } typedef enum { action_unknown, action_encrypt, action_decrypt } Action; int process_file(Action action, int key, FILE* source, FILE* target) { int ch = 0; while ( (ch = fgetc(source)) != EOF ) fputc( action == action_encrypt ? encrypt(key, ch) : decrypt(key, ch), target); return 0; } int main(int argc, char* argv[]) { if ( argc < 3 ) { // argv[]: 0 1 2 3 4 5 printf("Usage: caesar -ed key [SOURCE] [-W|TARGET]\n"); return 0; } Action action = action_encrypt; if ( strcmp(argv[1], "-d") == 0 ) action = action_decrypt; int key = atoi(argv[2]); FILE* source = stdin; if ( argc >= 4 ) { source = fopen(argv[3], "r"); if ( ! source ) return fprintf(stderr, "caesar: could not open %s\n", argv[3]); } bool overwrite = false; FILE* target = stdout; if ( argc >= 5 ) { const char* filename = argv[4]; if ( strcmp(argv[4], "-W") == 0 ) overwrite = filename = "caesar.temp"; target = fopen(filename, "w"); if ( ! target ) { fclose(source); return fprintf(stderr, "caesar: could not write %s\n", argv[4]); } } process_file(action, key, source, target); fclose(source); fclose(target); if ( overwrite) { remove(argv[3]); rename("caesar.temp", argv[3]); } return 0; }