C将struct dirent *转换为FILE *(C convert struct dirent * to FILE *)

编程入门 行业动态 更新时间:2024-10-24 12:27:54
C将struct dirent *转换为FILE *(C convert struct dirent * to FILE *)

我正在用C编写一个文件浏览器,它使用ls和cd的等价物来让用户导航文件系统并选择一个文件。 这一切都运行良好 - 我可以得到用户选择struct dirent *来表示他们想要选择的文件的目录条目。 但是,我想在我的程序中打开这个文件,我知道如何做的唯一方法是通过fopen(FILE* fptr) 。 有没有办法可以将struct dirent *转换为FILE* ? struct dirent有一个属性ino_t d_fileno ,它引用“文件序列号” - 是否与文件描述符相同? 我可以使用该文件描述符打开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*?

最满意答案

您不能将struct dirent * '转换'为FILE *因为第一个只与一个目录条目相关,无论它是文件,子目录还是别的,无论您是否拥有该文件的访问权限等等虽然您只能为已打开的文件设置FILE * 。 也。 没有办法通过它的inode打开文件,

可以做的是从你在opendir()和dir->d_name和fopen()中使用的目录名建立文件的路径名:

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; }

请注意,我假设,如果dirname不是绝对路径,则在调用opendir( dirname )和openfile( .... )之间不执行任何chdir() openfile( .... )

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( .... )

更多推荐

本文发布于:2023-08-05 20:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1439343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   dirent   struct   FILE   convert

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!