-1

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 :)

Giuseppe
  • 13
  • 1

1 Answers1

1

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");
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • What happens if the decrypted data is larger than the pipe's buffer? – Shawn Oct 24 '18 at 17:34
  • @Shawn You'll get a write error if that happens. Linux defaults to 64K, but that can be increased via `fcntl` using the `F_SETPIPE_SZ` option. – dbush Oct 24 '18 at 17:37
  • Thank you all for these answers in such a short time @dbush i have tried your code, and it works but seems it works only if the char* doesnt contain spaces. if the data contains a space, the program keep alive without doing anything. – Giuseppe Oct 24 '18 at 20:59
  • @Giuseppe glad I could help. Feel free to [accept this answer[(https://stackoverflow.com/help/accepted-answer) if you found it useful. – dbush Oct 24 '18 at 21:01
  • sorry, not spaces but returns char like "\n" – Giuseppe Oct 24 '18 at 21:04
  • I'll explain for example: if i set data = "helloworld" and len = 10 it works perfectly. but if data is = "hello world" and len = 11 the program keep alive doing nothing; but if len is = 5 (to the "o" of "hello") it works by writing only "hello" word. what's wrong? – Giuseppe Oct 24 '18 at 21:13
  • i fixed by replacing pipe(p) with _pipe(p, len, O_BINARY) – Giuseppe Oct 24 '18 at 21:36