C程序中如何读取目录中的文件并判断文件大小等信息
来源:     阅读:495
云上智慧
发布于 2020-04-24 20:20
查看主页

读取目录内容

应用程序可以用readdir系列函数来读取目录内容。

#include <sys/types.h>#include <dirent.h>DIR *opendir(const char *name);     //成功返回目录指针,失败返回NULLstruct dirent *readdir(DIR *dirp);  //成功返回目录项指针,已读完或者失败返回NULLint closedir(DIR *dirp);            //成功返回0,错误返回-1.

每次对readdir的调用返回的都是指向下一个目录项的指针,假如没有更多的目录项则返回NULL。每个目录项都是一个结构,形式如下:

struct dirent{    ino_t d_ino;        //inode值    char d_name[256];   //文件名}

假如出错,readdir也是返回NULL,但是它同时会设置errno。所以这时唯一区分错误还是流结束的线索,我们需要在程序中检查errno在readdir调用前后能否变化来检查有没有错误。

int main(int argc, char **argv){    DIR *streamp;    struct dirent *dep;       if(!(streamp = opendir(argv[1])))        exit(-1);        errno = 0;        while((dep = readdir(streamp)) != NULL){        printf("Found file:%s\n", dep->d_name);    }        if(errno != 0)        exit(-2);            if(closedir(streamp))        exit(-3);        exit(0);}

读取文件元数据

应用程序能够调用stat及fstat函数,检索到文件信息(或者称为文件元数据)。

#include <unistd.h>#include <sys/stat.h>int stat(const char *filename, struct stat *buf);int fstat(int fd, struct stat *buf);                                            //成功返回0,出错返回-1

下图列出结构体stat的详细成员:

struct stat {    dev_t   st_dev;     //设施    ino_t   st_ino;     //  inode    mode_t  st_mode;    //文件权限信息    nlink_t st_nlink;   //硬连接数    uid_t   st_uid;     //客户ID    gid_t   st_gid;     //组ID    dev_t   st_rdev;    //设施类型(假如是节点设施的话)    off_t   st_size;    //文件大小(字节)    unsignedlong st_blksize;    //块大小    unsignedlong st_blocks;     //块数目    time_t  st_atime;   //文件最后访问时间    time_t  st_mtime;   //文件最后修改时间    time_t  st_ctime;   //文件最后变动时间};

linux系统在stat.h中定义了宏谓词来确定st_mode成员的文件类型:

下面一个查询和解决一个文件st_mode位的示例:

int main (int argc, char **argv) {    struct stat stat;    char *type, *readok;       if (argc != 2) {    fprintf(stderr, "usage: %s <filename>\n", argv[0]);    exit(0);    }        Stat(argv[1], &stat);    if (S_ISREG(stat.st_mode))     /* Determine file type */    type = "regular";    else if (S_ISDIR(stat.st_mode))    type = "directory";    else     type = "other";    if ((stat.st_mode & S_IRUSR)) /* Check read access */    readok = "yes";    else    readok = "no";    printf("type: %s, read: %s\n", type, readok);    exit(0);}

获取更多知识,请点击关注:
嵌入式Linux&ARM
CSDN博客
简书博客


免责声明:本文为用户发表,不代表网站立场,仅供参考,不构成引导等用途。 系统环境 服务器应用
相关推荐
Python Scrapy爬取豆瓣Top250并存入mysql数据库,出现TypeError: can't concat bytes to tuple
前台面试每日 3+1 —— 第614天
Linux设置半中文环境(图形界面中文,字符界面英文)
Linux系统
Java架构之Nginx的五个特点
首页
搜索
订单
购物车
我的