Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void init_alpha(char *alpha)
{
const char *filename = "substitution.txt";
FILE *fin = fopen(filename, "r");
if (!fin)
{
perror(filename);
exit(EXIT_FAILURE);
}
memset(alpha, '-', 26);
for (int i = 0; i < 26; ++i)
{
int ch = fgetc(fin);
if (ch == EOF)
{
fprintf(stderr, "Error: less than 26 chars in subsitution file.\n");
exit(EXIT_FAILURE);
}
if (ch >= 'a' && ch <= 'z')
alpha[ch - 'a'] = i + 'a';
else if (ch >= 'A' && ch <= 'Z')
alpha[ch - 'A'] = i + 'a';
else
{
fprintf(stderr, "Error: bad character in substitution file.\n");
exit(EXIT_FAILURE);
}
}
fclose(fin);
if (memchr(alpha, '-', 26))
{
fprintf(stderr, "Error: not all characters in substitution file.\n");
exit(EXIT_FAILURE);
}
}
int main()
{
const char *filein = "encrypted.txt";
const char *fileout = "decrypted.txt";
char alpha[26];
init_alpha(alpha);
FILE *fin = fopen(filein, "r");
if (!fin)
{
perror(filein);
exit(EXIT_FAILURE);
}
FILE *fout = fopen(fileout, "w");
if (!fout)
{
perror(fileout);
exit(EXIT_FAILURE);
}
for (int ch; (ch = fgetc(fin)) != EOF; )
{
if (ch >= 'a' && ch <= 'z')
ch = alpha[ch - 'a'];
else if (ch >= 'A' && ch <= 'Z')
ch = toupper(alpha[ch - 'A']);
fputc(ch, fout);
}
fclose(fout);
fclose(fin);
return 0;
}