c 语言 求文件大小,C程序中如何读取目录中的文件并判断文件大小等信息

读取目录内容

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

#include

#include

DIR *opendir(const char *name); //成功返回目录指针,失败返回NULL

struct dirent *readdir(DIR *dirp); //成功返回目录项指针,已读完或失败返回NULL

int 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

#include

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成员的文件类型:

S_ISREG(m) :这是一个普通文件吗?

S_ISDIR(m) :这是一个目录文件吗?

S_ISSOCK(m) :这是一个网络套接字吗?

下面一个查询和处理一个文件st_mode位的示例:

int main (int argc, char **argv)

{

struct stat stat;

char *type, *readok;

if (argc != 2) {

fprintf(stderr, "usage: %s \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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值