Skip to content

Commit 77034e4

Browse files
committed
pgm 22.14, encrypt a character stream
1 parent 0fef012 commit 77034e4

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,3 +177,4 @@ spec/parts-list-io-spec
177177
22/22.11-format-dates
178178
22/22.13-find-departure
179179
22/22.13-find-departure-unbuffered
180+
22/22.14-ceasar-cipher

22/22.14-ceasar-cipher.c

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <stdio.h>
2+
#include <string.h>
3+
#include <stdlib.h>
4+
#include <ctype.h>
5+
6+
#define INPUT_FILENAME_SIZE FILENAME_MAX - 4
7+
#define OUTPUT_FILENAME_SIZE FILENAME_MAX
8+
9+
int main(void)
10+
{
11+
char input[INPUT_FILENAME_SIZE + 1];
12+
char output[OUTPUT_FILENAME_SIZE + 1];
13+
int ch, i, shift_amount;
14+
int rc = 0;
15+
16+
printf("Enter name of file to be encrypted: ");
17+
18+
for (i = 0; i < INPUT_FILENAME_SIZE && (ch = getchar()) != '\n'; i++) {
19+
input[i] = output[i] = ch;
20+
}
21+
input[i] = output[i] = '\0';
22+
strcat(output, ".enc");
23+
24+
printf("Enter shift amount (1-25): ");
25+
scanf("%d", &shift_amount);
26+
27+
FILE *istream, *ostream;
28+
if ((istream = fopen(input, "r")) == NULL) {
29+
perror(input);
30+
exit(EXIT_FAILURE);
31+
}
32+
33+
if ((ostream = fopen(output, "w")) == NULL) {
34+
perror(output);
35+
if (fclose(istream) == EOF)
36+
perror(input);
37+
exit(EXIT_FAILURE);
38+
}
39+
40+
while ((ch = fgetc(istream)) != EOF) {
41+
if (islower(ch))
42+
ch = (( ch - 'a') + shift_amount) % 26 + 'a';
43+
if (isupper(ch))
44+
ch = (( ch - 'A') + shift_amount) % 26 + 'A';
45+
if (fputc(ch, ostream) == EOF) {
46+
perror(output);
47+
rc = -1;
48+
break;
49+
}
50+
}
51+
if (ferror(istream)) {
52+
perror(input);
53+
rc = -2;
54+
}
55+
56+
if (fclose(istream) == EOF) {
57+
perror(input);
58+
rc = -3;
59+
}
60+
61+
if (fclose(ostream) == EOF) {
62+
perror(output);
63+
rc = -4;
64+
}
65+
66+
return rc;
67+
}

0 commit comments

Comments
 (0)