// caesar.c -- example for CS 2505 notes // Usage: caesar // #include #include #include #include int checkParams(int nparams, char** params); int checkShiftAmt(char* src); int setShiftAmt(char* src); int processFile(int shiftAmt, char* fileName); char applyShift(char Original, int shiftAmt); #define WRONG_NUMBER_OF_PARAMS 1 #define INVALID_SHIFT_SPECIFIED 2 #define FILE_NOT_FOUND 3 int main(int argc, char** argv) { int ckStatus; if ( ( ckStatus = checkParams(argc, argv) ) != 0 ) { return ckStatus; } int shiftAmt = setShiftAmt(argv[1]); printf("Shifting alphabetic input text by %d positions.\n", shiftAmt); int charsShifted = processFile(shiftAmt, argv[2]); printf("Shifted %d alphabetic characters.\n", charsShifted); return 0; } int processFile(int shiftAmt, char* fileName) { shiftAmt = ((shiftAmt % 26) + 26) % 26; int nChars = 0; FILE *In = fopen(fileName, "r"); char nextIn, nextOut; while ( fscanf(In, "%c", &nextIn) == 1 ) { if ( isalpha(nextIn) ) { ++nChars; nextOut = applyShift(nextIn, shiftAmt); } else nextOut = nextIn; printf("%c", nextOut); } fclose(In); return nChars; } char applyShift(char Original, int shiftAmt) { char Modified = Original; //. . . return Modified; } int checkParams(int nparams, char** params) { if ( nparams != 3 ) { printf("Invoke as: caesar \n"); return WRONG_NUMBER_OF_PARAMS; } if ( !checkShiftAmt(params[1]) ) { return INVALID_SHIFT_SPECIFIED; } FILE* fp; if ( (fp = fopen(params[2], "r") ) == 0 ) { printf("The file %s could not be found.\n", params[2]); return FILE_NOT_FOUND; } fclose(fp); return 0; } int checkShiftAmt(char* src) { char *p; errno = 0; int result = (int) strtol(src, &p, 10); return (errno == 0 && *p == 0 && p != src); } int setShiftAmt(char* src) { char *p; int shiftAmt = strtol(src, &p, 10); return shiftAmt; }