-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileDecryption.c
60 lines (53 loc) · 1.55 KB
/
fileDecryption.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdlib.h>
#define FILENAME "results.txt"
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Missing 1 or 2 arguments\n");
return 0;
}
const char key = *(argv[1]);
const char* filename = argv[2];
int rc = 0;
FILE *binFileDescriptor = fopen(filename, "r");
// Error checking: Check if file exists or not
if (!binFileDescriptor) {
printf("ERROR: %s does not exist\n", filename);
return -1;
}
// If the file does exist, continue encrypting
// The program calculates the size of the file
fseek(binFileDescriptor, 0, SEEK_END);
unsigned long fsize = ftell(binFileDescriptor);
printf("fsize = %lu\n", fsize);
fseek(binFileDescriptor, 0, SEEK_SET);
// Read the data
char *decryption = (char *) malloc(fsize);
char *decryptionStart = decryption;
if (decryption == NULL) {
printf("ERROR: Cannot malloc decryption array\n");
fclose(binFileDescriptor);
return -2;
}
while (1) {
// Read one character using fgetc
char readChar = fgetc(binFileDescriptor);
if (readChar == EOF) {
break;
}
// Decrypt character
*decryption++ = readChar ^ key;
} // while (1) {
FILE *fd = fopen(FILENAME, "w");
if (!fd) {
printf("ERROR: Cannot open file %s\n", FILENAME);
rc = -3;
}
else {
fwrite(decryptionStart, fsize, 1, fd);
}
fclose(fd);
free(decryptionStart);
fclose(binFileDescriptor);
return rc;
}