您的位置:首页 > 运维架构 > Linux

文件和目录属性

2016-06-28 19:59 337 查看

文件和目录

文件属性的获取

返回filename有关的信息的结构体,然后放到buf中。

int stat(const char* filename, struct stat *buf);


将已经打开的文件(fd所描述的文件)的信息保存到buf中。

int fstat(int fd, struct stat *buf);


类似于stat,只是当filename是一个符号链接,类似与快捷方式时,buf中保存的是该符号链接的有关信息,而不是所链接的文件的信息。

其中,struct stat结构体保存着文件相关的信息,包括结点号, 用户id,

文件大小st_size等等。

int lstat(const char* filename, struct stat *buf);


文件类型的检测

利用宏来确定文件类型,一下这些宏都是struct stat结构体中st_mode的成员。

S_ISREG(m)  // 判断m是不是一个regular file
S_ISDIR     // 文件夹
...


目录操作

#include <sys/types.h>
#include <dirent.h>
//改变工作路径,成功返回0,失败返回-1
int chdir(const char *path); //改变目录到path
int fchdir(int fd);//区别在于,fd是目录的文件描述符而已
//打开目录name,成功返回目录指针
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
//访问文件夹dirname/,并把文件夹下的内容保存到struct dirent结构体中
struct dirent *readdir(DIR* dirname);

struct dirent {
ino_t d_ino;   /* inode number */
off_t d_off;   /* not an offset; see NOTES */
unsigned short d_reclen;  /* length of this record */
unsigned char  d_type;   /* type of file; not supported by all filesystem types */
char d_name[256]; /* filename */
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息