For a lab I’ve got to do, I need to create a program that will take a simple string from a text file and encrypt it using a key – a number between 0 and 255. It will read the file into an array and encrypt (or decrypt) this array into another array by XOR-ing each byte with the key. In the end, it writes the modified array into a second file.
I’ve mostly got it – what I have below compiles just fine. It doesn’t, however, copy anything to the second file. Help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CRYPT(a, b) (a ^ b)
int main(int argc, char *argv[])
{
FILE *fp1, *fp2;
int a[100], b, key;
int i = 0;
// opens file containing string to be encrypted
if((fp1 = fopen(argv[2], "rb")) == NULL)
{
printf("Error - could not open file or file does not exist\n");
return;
}
// opens file encrypted string will be saved to
fp2 = fopen(argv[3], "wb");
// converts string to integer
key = atoi(argv[1]);
while(fread(a, sizeof(a), 100, fp1))
{
while (i != '\0');
{
b = CRYPT(a[i], key);
fwrite(&b, sizeof(a), 1, fp2);
i++;
}
}
return 0;
}
I think the problem lies here –
You are initializing
ito 0 and in the while loop you are checking whether or not i is equal toNULL. The integer value ofNULL, or\0is 0. As a result, the expression is false and your loop is never being executed.Also remove the extra semi-colon at the end of this
whileloop.From the reference –
So you also need to change your
freadfunction to this –Similarly, you also need to change your fwrite –
The edited code should look something like this –