In: Computer Science
Programming Language C++
Encrypt a text file using Caesar Cipher.
Perform the following operations:
#include <iostream>
using namespace std;
int main() {
// write code here
}
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
void encrypt(char *text, int s)
{
FILE *fptr;
fptr = fopen("program.txt", "w+");
int len = strlen(text);
char result[len+1];
int j=0 ;
for (int i=0;i<strlen(text);i++)
{
if (isupper(text[i]))
result[j]= char(int(text[i]+s-65)%26 +65);
else if(islower(text[i]))
result[j]=
char(int(text[i]+s-97)%26 +97);
else
result[j]=text[i];
j++;
}
result[j]='\0';
fprintf(fptr,"%s",result);
fclose(fptr);
}
int main()
{
char buffer[1000];
char buff[1000];
FILE *fptr;
fptr = fopen("program.txt", "w+");
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter the text to be tested for cipher use $ as last
character and press enter to end\n");
fgets(buffer, sizeof(buffer), stdin);
fprintf(fptr,"%s", buffer);
fclose(fptr);
fptr = fopen("program.txt", "r");
char c;
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
c = fgetc(fptr);
int i=0;
while (c!='$'&&c != EOF)
{
buffer[i]=c;
c = fgetc(fptr);
i++;
}
buffer[i]='\0';
fclose(fptr);
encrypt(buffer, 5);
fptr = fopen("program.txt", "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
cout<<"File content is"<<endl;
c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
return 0;
}