Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <stdio.h>
- #include <stdbool.h>
- #include <stdlib.h>
- #include <string.h>
- void initializeEncryptArray(char key[], char encrypt[]);
- void initializeDecryptArray(char encrypt[], char decrypt[]);
- char * removeDuplicates(char word[]);
- int targetFound(char charArray[], int num, char target);
- void processInput(FILE *inf, FILE * outF, char substitute[]);
- int main(int argc, char * argv[])
- {
- int choice;
- char *ch;
- bool loop = true;
- FILE *fin, *fout;
- if (argc != 5)
- {
- printf ("Usage: cipher option key infile, outfile\n");
- printf ("Option 1 for encryption and 2 for decryption\n");
- exit(1);
- }
- choice = atoi(argv[1]);
- char *k = argv[2];
- fin = fopen(argv[3], "r");
- fout = fopen(argv[4], "w");
- if (fin == NULL || fout == NULL)
- {
- printf("File could not be opened\n");
- exit(1);
- }
- char encrypt[26], decrypt[26];
- initializeEncryptArray(k, encrypt);
- initializeDecryptArray(encrypt, decrypt);
- if (choice == 1){
- processInput(fin, fout, encrypt);
- }else if (choice == 2){
- processInput(fin, fout, decrypt);
- }else {
- printf ("Usage: cipher option key infile, outfile\n");
- printf ("Option 1 for encryption and 2 for decryption\n");
- exit(1);
- }
- fclose(fin);
- fclose(fout);
- return 0;
- }
- void initializeEncryptArray(char key[], char encrypt[])
- {
- int i = 0, j = 90;
- char *endkey = removeDuplicates(key);
- printf("%s\n", endkey);
- while(endkey[i] != '\0'){
- encrypt[i] = endkey[i];
- i++;
- }
- while(j >= 65){
- if (targetFound(encrypt, i, (char)j) != 0){
- encrypt[i] = (char)j;
- i++;
- }
- j--;
- }
- printf("Finished encryption.\n");
- printf("%c\n", encrypt[0]);
- }
- void initializeDecryptArray(char encrypt[], char decrypt[])
- {
- int i = 0, j = 0;
- while (i < 26){
- decrypt[((int)(encrypt[i]))-65] = (char) (i + 65);
- i++;
- }
- }
- char * removeDuplicates(char word[]){
- int i, j;
- bool match = false;
- char *result = "";
- char end[26] = "";
- for (i = 0; i < (strlen(word)+1); i++){
- if (i < strlen(word)){
- for (j = 0; j <= strlen(end); j++){
- if (end[j] == word[i]){
- match = true;
- }
- }
- if (match != true){
- end[i] = word[i];
- }
- }else {
- end[i] = '\0';
- }
- }
- word = end;
- return word;
- }
- int targetFound(char charArray[], int num, char target){
- int i = 0;
- while (i <= num){
- if (charArray[i] == target){
- return 1;
- }
- i++;
- }
- return 0;
- }
- void processInput(FILE *inF, FILE * outF, char substitute[]){
- int parsed = 0;
- char ch;
- while ( fscanf(inF, "%s", &ch) != EOF ){
- if(isupper(ch)){
- parsed = ((char) ch) - 65;
- fprintf(outF, "%c", substitute[parsed]);
- }else if(islower(ch)){
- parsed = ((char) ch) - 97;
- fprintf(outF, "%c", substitute[parsed + 32]);
- }else {
- parsed = ch;
- fprintf(outF, "%c", substitute[parsed]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement