Search code examples
cfileencryptionfopen

cast char* to FILE* without saving the file


im trying to open an existing file in "rb" mode and i need to decrypt returning a new FILE* without overwrite the original file or creating new temporary one. in short words, i need something like this:

FILE *decrypt(){
    FILE *cryptedfile = fopen("file.ext", "rb");

    //... my decrypter code

    return (the decrypted file as FILE*).
}

so, there is a way to do something like "cast char* to FILE*"?

i have tried many different solutions without success, i have also tried to create a new tmpfile() but the result seems do not work properly and i do not want to create a tmpfile anyway, but just keep it into the memory.

thanks :)


Solution

  • After decrypting the data, you can create a pipe to feed the decrypted data into, then you can return the read end of the pipe to read the data.

    FILE *decrypt(){
        FILE *cryptedfile = fopen("file.ext", "rb");
    
        char *data;
        int len;
        // load decrypted data into "data" and length info "len"
    
        int p[2];
        if (pipe(p) == -1) {
            perror("pipe failed");
            return NULL;
        }
    
        int rval;
        if ((rval = write(p[1], data, len)) == -1) {
            perror("write failed");
            close(p[0]);
            close(p[1]);
            return NULL;
        } else if (rval < len) {
            printf("write failed, wrote %d, expected %d\n", rval, len);
            close(p[0]);
            close(p[1]);
            return NULL;
        }
    
        return fdopen(p[0], "r");
    }
    

    Alternately, you can also use fmemopen:

    FILE *decrypt(){
        FILE *cryptedfile = fopen("file.ext", "rb");
    
        char *data;
        int len;
        // load decrypted data into "data" and length info "len"
    
        return fmemopen(data, len, "rb");
    }