Reputation: 29
So I want to make kind of an encryption program for a school project,I want for example the letter 'a' to be replaced with:12345 'b' with 54321 in C,how can I accomplish this?I'm not the best,my code so far:
eFile = fopen("Message.txt", "ab+");
while(!feof(eFile))
{
fscanf(eFile,"%c",&message);
}
I want for example if I write the word apple into the text file,make the program scan it letter by letter and replace every letter with a 5 digit number(I have them predefined already) example: apple = 12342 69865 69865 31238 43297
Upvotes: 1
Views: 1666
Reputation: 60058
I'm not sure if your strategy can be called encryption, but it can be easily accomplished with a lookup table.
Simply put the replacements in an int table like so:
int map[]={ //size will be autoinferred to fit the indices
['a']=12342,
['p']=69865,
['l']=31238,
['e']=43297,
//you should preferrably have an entry for each value of char
};
And use it to print the replacements.
int c;
while(EOF!=(c=fgetc(inputFile)))
if(0>(outPutfile,"%d \n", map[c]))
return -1;
Since the size of the new file will unpredictably change, it'd probably be a good idea to output into a temporary file and then move it in the place of the original after it's successfully finished.
A better idea might be to simply forget about in-place file rewriting
and simply read stdin
and write to stdout
– that would allow the program to handle streams well as well and a possibly wrapper script could turn it into an inplace translator (via the temp file) after the fact if needed.
Upvotes: 1
Reputation: 140970
_
#include <stdio.h>
#include <assert.h>
int cipher_table[255] = {
['a'] = 12342,
['p'] = 69865,
['l'] = 31238,
['e'] = 43297,
// so on...
};
int main()
{
FILE *fin = stdin; // fopen(..., "r");
assert(fin != NULL);
FILE *fout = stdout; // tmpfile();
assert(fout != NULL);
for (int c; (c = getc(fin)) != EOF;) {
if (c == '\n') {
if (fputc('\n', fout) == EOF) {
fprintf(stderr, "Error writing to file fout with fputc\n");
return -1;
}
continue;
}
if (fprintf(fout, "%5d ", cipher_table[c]) < 0) {
fprintf(stderr, "Error writing to file fout with fprintf\n");
return -1;
}
}
close(fin);
close(fout);
return 0;
}
Upvotes: 2