I'm new to the site and to C! I'm trying to write an encryption/decryption program, but I've ran into a problem - my decrypted files aren't showing as characters but instead "[]". Perhaps someone could suggest where I've gone wrong - I think my decryption section is missing something! The program is meant to read commands from arguments(-e encrypt, -d decrypt, -i input file name, -o output file name, -a algorithm, -k key). Here follows my code (go easy!):
#include <stdio.h>
int main(int argc, char *argv[])
{
if (strcmp(argv[1], "-e") == 0)
{
printf("\tEncrypting...\n");
//File pointer input, 4th arg as filename, read
FILE *fpi = fopen(argv[3],"r");
if (fpi == NULL)
{
printf("\tError opening file!\n");
exit(0);
}
//Find size of file
int sz;
fseek(fpi, 0, SEEK_END);
sz = ftell(fpi);
printf("\tLength of file is: %i\n", sz);
fseek(fpi, 0, SEEK_SET);
//10th arg is key
int key = atoi(argv[9]);
//I want to make a default key if not supplied in args
//Not sure how to write, this crashes :(
if(!argv[9])
{
key = 200;
}
printf("\tYour key is: %d\n", key);
// Encryption; does the job
char input[512];
while(fgets(input, 512, fpi))
{
FILE *fpo = fopen(argv[5], "w+");
int i=0;
while (input[i] != 0)
{
fprintf(fpo, "%04x ",input[i]+key << 2);
i++;
}
}
printf("\tEncryption complete, exiting...\n");
fclose(fpi);
//When I try to fclose(fpo) here it crashes
}
else if (strcmp(argv[1], "-d") == 0)
{
printf("\tDecrypting...\n");
FILE *fpi = fopen(argv[3],"r");
if (fpi == NULL)
{
printf("\tError opening file!\n");
exit(0);
}
int key = atoi(argv[9]);
printf("\tUsing key: %d\n", key);
char input[512];
while( fgets(input, 512, fpi))
{
FILE *fpo = fopen(argv[5], "w+");
int i=0;
while (input[i] != 0)
{ //tried the reverse - returns [][][][]
fprintf(fpo, "%c ",input[i] - key >> 2);
i++;
}
}
printf("\tDecryption complete, exiting...\n");
fclose(fpi);
}
else
{
printf("\tUsage: -e/-d, -i input file name, -o output file name, -a alg to use, -k key value.\n\tAlgorithms supported: basic\n");
}
return 0;
}
Thanks in advance for any help!
Aucun commentaire:
Enregistrer un commentaire