cfile-iofilesystemsdirent.h

C convert struct dirent * to FILE *


I'm writing a file browser in C that uses the equivalent of ls and cd to let the user navigate the filesystem and select a file. It's all working well - I can get as far as the user selecting a struct dirent * that represents the directory entry of the file they want to choose. However, I want to open this file in my program, and the only way I know how to do that is through fopen(FILE* fptr). Is there a way I can convert a struct dirent * to a FILE*? A struct dirent has a property ino_t d_fileno which refers to "the file serial number" - is that the same as a file descriptor? Could I use that file descriptor to open a FILE*?


Solution

  • You can't 'convert' a struct dirent * to FILE * because the first is just related to one directory entry no matter if it's a file, a sub directory or something else, no matter whether you have access rights to the file and so on while you can only have a FILE * for a file you have opened. Also. there's no way to open a file by it's inode,

    What you can do, is building the file's pathname from the directory's name as you have used in opendir() and dir->d_name and fopen() that pathname:

     FILE *openfile( const char *dirname, struct dirent *dir, const char *mode )
     {
           char pathname[1024];   /* should alwys be big enough */
           FILE *fp;
    
           sprintf( pathname, "%s/%s", dirname, dir->d_name );
           fp = fopen( pathname, mode );
           return fp;
     }
    

    Please note that I assume that, if dirname is not an absolute path, you don't do any chdir()s between calling opendir( dirname ) and openfile( .... )