I am trying to write a simple C program that encrypts a text file using the offset cipher.
Here is what I want the program to do:
- Take a text file, read it character by character and after incrementing each character by some integer value (which increments the ASCII value of the character, resulting in some completely different characters to be obtained) overwrite the original text file such that it gets encrypted.
Here is my code: I am using an additional file named text.txt to store modified data and copy it back to the original file (named file.txt)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void encrypt(char *filename) {
FILE *fp, *ft;
int key = 1;
char ch;
fp = fopen(filename, "r+");
ft = fopen("temp.txt", "w+");
if (fp == NULL) {
printf("Unable to open file");
exit(1);
}
if (ft == NULL) {
printf("Unable to generate encryption key");
exit(2);
}
//modifying ASCII values and storing it in temp.txt
while (1) {
ch = fgetc(fp);
if (ch == EOF)
break;
ch = ch + key; //offset
fputc(ch, ft);
}
rewind(fp);
rewind(ft);
//copying temp to original file
while (1) {
ch = fgetc(ft);
if (ch == EOF)
break;
fputc(ch, fp);
}
printf("The file has been encrypted successfully");
fclose(fp);
fclose(ft);
}
void decrypt(char *filename) {
FILE *fp, *ft;
char ch;
fp = fopen(filename, "r+");
ft = fopen("temp.txt", "w+");
if (fp == NULL) {
printf("Unable to open file");
exit(1);
}
if (ft == NULL) {
printf("Unable to access encryption key");
exit(2);
}
//decrementing the chars by the same ASCII value to get back original text into temp.txt
while (1) {
ch = fgetc(fp);
if (ch == EOF)
break;
ch = ch - 1;
fputc(ch, ft);
}
rewind(fp);
rewind(ft);
//copying decrypted data to original file
while (1) {
ch = fgetc(ft);
if (ch == EOF)
break;
fputc(ch, fp);
}
printf("File Decrypted Successfully");
}
int main(void) {
int choice;
char name[100], ch;
FILE *fs, *ft;
printf("To encrypt/decrypt a file: ");
while (1) {
printf("\nMENU");
printf("\n1.Encrypt\n2.Decrypt\n");
printf("Enter your choice: ");
scanf("%d", &choice);
fflush(stdin);
switch (choice) {
case 1:
printf("Enter the name of the file to be encrypted: ");
fgets(name, 99, stdin);
strtok(name,"\n");
encrypt(name);
return 0;
break;
case 2:
printf("Enter the name of the file to be decrypted: ");
fgets(name, 99, stdin);
strtok(name,"\n");
decrypt(name);
return 0;
break;
}
}
}
But, the problem is that the encypt
function works as expected while modifying the original file and storing it in temp.txt, but when it is copying the temp.txt file back into the original file, the last character is not being overwritten.
Below are some links to the output screenshots
What is wrong with my code? does it have to do something with the EOF
of temp.txt or am I missing something obvious?