سؤال

I'm setting up the FUSE filesystem, and I need to get a file pointer to any open files so that I can encrypt them as they get written. The FUSE system uses a special struct. One of the components of the struct is called fh and is of type uint64_t. When a file is opened, it is captured in an int variable as you can see in the following code:

/* File open operation */
int bb_open(const char *path, struct fuse_file_info *fi)
{
    int fd;   
    fd = open(path, fi->flags);
    fi->fh = fd;
    return fd;
}

This fi struct is available to me in the write function, and I'm hoping that I can use it to create a file pointer that I can pass to my encryption function. Here is the code for the write function as I have it set up at the moment:

/* Write data to an open file */
int bb_write(const char *path, const char *buf, size_t size, off_t offset,
         struct fuse_file_info *fi)
{
    char* password;
    FILE* fp;
    //malloc and instantiate password
    fp = (FILE*) fi->fh; //my lame attempt to get a file pointer
    return encrypt(<inpFilePtr>, <outFilePtr>, 1, password);
}

Finally, the signature of my encryption function looks like this:

extern int encrypt(FILE* in, FILE* out, int action, char* key_str);

I'd like to take that fi->fh variable and turn it into a file pointer so that I can use it as my input file pointer argument. Since it was originally created by an "open" operation, it seems like there should be a way to do this, but I can't make it work.

Can anyone help? Thanks!

هل كانت مفيدة؟

المحلول

File descriptors and FILE * pointers aren't the same thing. A FILE * pointer is a pointer to an opaque type provided by your C implementation - the APIs that deal with FILE * (fopen, fread, fwrite, fclose, etc.) are part of standard C. File descriptors, on the other hand, are operated on using the POSIX system calls (open, read, write, close, etc.) that are often used to implement the C-level abstractions.

Luckily there are functions that let you get one from the other. In your case, you'll want to use fdopen(3) to get a FILE * from the file descriptor. If you wanted to go the other way, you'd want to look into fileno(3).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top