Search code examples
cencryptionxor

no output to disk implementing xor encryption in c


I have an odd problem: The following code is meant to implement xor encryption, but I am having trouble debugging why nothing is written to the disk. I am thinking I am using fseek or fputc improperly. The following is a working example of my issue. What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *key, *data;
    char keyf[] = "/sdcard/key";
    char dataf[128];
    int c0, c1, c2;
    long int i;

    key = fopen(keyf, "r+");
    if (key == NULL) {
        printf("%s missing\n", keyf);
        exit(1);
    }
    printf("data file:\n");
    i = 0;
    while ((c0 = getc(stdin)) != '\n' &&
           i < 128)
        dataf[i++] = (char)c0;
    data = fopen(dataf, "r");
    if (data == NULL) {
        printf("%s missing\n", dataf);
        exit(2);
    }
    i = 0;
    while ((c0 = fgetc(key)) != EOF &&
           (c1 = fgetc(data)) != EOF) {
        while (!c0) c0 = fgetc(key);
        c2 = c0 ^ c1;
        fseek(data, i++, SEEK_SET);
        fputc(c2, data);
        printf("%c", c2);
    }
    fflush(data);
    fclose(key);
    fclose(data);
    return 0;
}

Solution

  • You've opened data as read-only. You will need to open it for read-write, and you don't want truncation, so you will want mode "r+", which opens the file for reading/writing with the position at the start for both.. As you read from the file, the file pointer will be incrementing, so to write back over the character you just read, you will also need to seek with fseek() to go back.

    Here is a link to the fopen man page which describes access modes.

    This is the fseek man page which will describe how to move your file position around.