c-programming

Simple C programs
git clone git://git.laack.co/c-programming.git
Log | Files | Refs

shift-cipher.c (1696B)


      1 #include <stdio.h>
      2 #include <stdbool.h>
      3 #include <stdlib.h>
      4 #include <ctype.h>
      5 
      6 char rotate(char in, int rotateBy){
      7     char result = in;
      8 
      9     if( islower(in) ){
     10         char offset = in - 'a';
     11         int res = offset + rotateBy;
     12         while(res < 0){
     13             res += 26;
     14         }
     15         result = ((res) % 26) + 'a';
     16     }
     17     else if( isupper(in) ){
     18         char offset = in - 'A';
     19         if(offset < 0){
     20             offset += 26;
     21         }
     22         int res = offset + rotateBy;
     23         while(res < 0){
     24             res += 26;
     25         }
     26         result = ((res) % 26) + 'A';
     27 
     28     }
     29     else if (isalnum(in)){
     30         char offset = in - '0';
     31         if(offset < 0){
     32             offset += 10;
     33         }
     34         int res = offset + rotateBy;
     35         while(res < 0){
     36             res += 10;
     37         }
     38         result = ((res) % 10) + '0';
     39     }
     40 
     41     return result;
     42 }
     43 
     44 int main(int argc, char *argv[]){
     45 
     46     int opt;
     47 
     48 
     49 
     50     if (argc < 4){
     51         printf("Usage: shift {input_file} {output_file} {rotate_by}\n");
     52         return -1;
     53     }
     54 
     55     char* inputFileName;
     56     inputFileName = argv[1];
     57     
     58     char* outputFileName;
     59     outputFileName = argv[2];
     60 
     61 
     62     int rotateBy = atoi(argv[3]);
     63 
     64     FILE *fptr = fopen(inputFileName, "r");
     65     
     66     if (fptr == NULL){
     67         printf("Bad input file. \n");
     68         return -1;
     69     }
     70 
     71     FILE *outPtr = fopen(outputFileName, "w");
     72 
     73     int readIn = 100;
     74     char next[readIn];
     75     char nextCipher[readIn];
     76 
     77     while(fgets(next, readIn, fptr)){
     78         for (int itr = 0; next[itr] != 0; ++itr){
     79             nextCipher[itr] = rotate(next[itr], rotateBy);
     80             fputc(nextCipher[itr], outPtr);
     81         }
     82     }
     83 
     84     fclose(fptr);
     85     fclose(outPtr);
     86 }