#include
#include
#include
int lstat(const char * restrict path, struct stat * restrict buf);
int stat(const char *restrict path, struct stat * restrict buf);
int fstat(int fd,struct stat *buf);
lstat和stat区别:
对于软链来说:
lstat返回软链本身的状态
stat返回软链所指文件的状态
struct stat:
struct stat{
dev_t st_dev; /*包含文件的设备号*/
ino_t st_ino; /*文件inode序列号 */
mode_t st_mode;/*文件的mode*/
nlink_t st_nlink; /*硬链接的数量*/
uid_t st_uid; /*文件的用户id*/
gid_t st_gid; /*文件的goup id*/
off_t st_size;/*文件大小*/
time_t st_atime;/*最后一次访问时间*/
time_t st_mtime;/*最后一次修改时间*/
time_t st_ctime;/*最后一次状态改变时间*/
}
例子:
#include
#include
#include
int isdirectory(char *path) {
struct stat statbuf;
if (stat(path, &statbuf) == -1)
return 0;
else
return S_ISDIR(statbuf.st_mode);
}
2、文件权限:
设置文件权限的系统调用:
#include
#include
int chmod(const char *path, mode_t mode);
int fchmod(int fd,mode_t mode);
成功返回0,失败返回-1,并设置errno:
EACCESS:没有搜索path的权限
EBADF:fd不合法的文件描述符(仅fchmod)
EFAULT:path不合法的指针(仅chmod)
EIO:文件系统内部I/O错误
ELOOP:由于symbolic link导致解析path死循环
ENAMETOOLONG:path太长(仅chmod)
ENOENT:path不存在
ENOME:内存不足
ENOTDIR:不是一个目录(仅chmod)
EPERM:进程不是文件的owner或者缺少CAP_FOWNER能力。
EROFS:文件在只读文件系统中。
chomd:
ret = chmod("./map.png",S_IRUSR | S_IWUSR);
if(ret)
perror("chmod");
int ret;
ret = fchmod(fd, S_IRUSR | S_IWUSR);
if(ret)
perror("fchmod");