Write a function in C (only C) to operate below task. Or if not a function, writ
ID: 3770865 • Letter: W
Question
Write a function in C (only C) to operate below task. Or if not a function, write a series of statement to excute below task.
Open a file Decrypt_hello.txt to write. You need to read each character from Encrypt_Hello.txt and write to Decrypt_hello.txt following a rule of decryption.
Decryption rule: Start reading characters from the beginning of the input file and calculate the xor of the adjacent two characters and write the result to output file. First character from input file will be written into output file without any change.
For example: Input stream of data 1 1 0 1 1 0
xor of adjacent two bits 1 (1 ^ 1) (1 ^ 0) (0 ^ 1) (1 ^ 1) (1 ^ 0)
Output stream of data 1 0 1 1 0 1
Finally close all three files - Hello.txt, Encrypt_hello.txt, Decrypt_hello.txt.
Explanation / Answer
C Program:
#include <stdio.h>
#include <stdlib.h>
char xor(int, int);
int main ()
{
int i,j,v1,v2;
int count = 0;
char *array, *oarray;
char ch = '';
// open file
FILE *file = fopen( "data.txt", "r" );
clrscr();
// count number of characters in a file
while ((ch=fgetc(file)) != EOF)
count++;
// declare array
array = (char*) calloc(count, sizeof(char));
oarray = (char*) calloc(count, sizeof(char));
rewind(file);
// read in the file to the array
for(i=0; i<count; i++)
fscanf(file, "%c", &array[i]);
// print the array
for(i=0; i<count-1; i++)
{
printf("*** %c **", array[i]);
v1 = array[i] - '0';
v2 = array[i+1] - '0';
oarray[i] = xor(v1, v2);
}
fclose( file );
file = fopen("data1.txt","w");
fprintf(file,"%c",array[0]);
fprintf(file,"%s",oarray);
fclose(file);
getch();
return 0;
}
char xor(int v1, int v2)
{
char res;
int r;
if(v1 == 1 && v2 == 1)
r = 0;
else if(v1 == 0 && v2 == 1)
r = 1;
else if(v1 == 1 && v2 == 0)
r = 1;
else
r = 0;
res = r + '0';
return res;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.