1

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

2 Answers2

2
  • read character by character from input
  • use simple array to convert between character to number or to string, or use a handler function for that
  • print that number
  • replacing is not easy, simplest way is to create a tempfile, write numbers to that tempfile, than copy the tempfile to the original file and remove tempfile.

_

#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;
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

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.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142