1、文件的属性都在如下的结构体当中
2、文件属性操作API
(1)、 int stat(const char* pathname, struct stat* buf);
(2)、 int fstat(int fd , struct stat * buf);
(3)、 int lstat(const char * pathname , struct stat* buf);
功能:返回与pathname 或 fd 指定的文件属性信息,存储在buf中。
lstat与stat的区别:当文件是一个符号链接时,lstat返回符号链接的有关信息,而不是符号链接指向的文件的信息。
3、Linux中的七种文件和七种宏
普通文件(regular file ) S_ISREG()
目录文件(directory file) S_ISDIR()
块特殊文件(block special file) S_ISBLK()
字符特殊文件(character special file) S_ISCHR()
FIFO(named pipe) S_ISFIFO()
套接字(socket) S_ISSOCK()
符号链接(symbolic link) S_ISLNK()
测试一下符号链接文件(软连接和硬链接):
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char ** argv)
{
if(argc < 2)
{
printf("usage: %s file path\n",argv[0]);
return 0;
}
struct stat buf;
int i = 0;
for(i = 1; i < argc;i++)
{
memset(&buf,0,sizeof(struct stat));
if(lstat(argv[i],&buf) < 0)
{
printf("%s lstat error\n",argv[i]);
continue;
}
printf("%-20s",argv[i]);
printf("ino:%d,st_dev:%d,nlink:%d,uid:%d,gid:%d ",buf.st_ino,buf.st_dev,buf.st_nlink,buf.st_uid,buf.st_gid);
//是否是普通文件
if(S_ISREG(buf.st_mode))
{
printf("normal file\n");
}
//是否是目录
else if(S_ISDIR(buf.st_mode))
{
printf("directory\n");
}
//是否是块设备文件
else if(S_ISBLK(buf.st_mode))
{
printf("is block file\n");
}
//是否是字符设备文件
else if(S_ISCHR(buf.st_mode))
{
printf("char file\n");
}
//fifo 文件
else if(S_ISFIFO(buf.st_mode))
{
printf("fifo file\n");
}
//套接字文件
else if(S_ISSOCK(buf.st_mode))
{
printf("socket file\n");
}
//符号链接文件
else if (S_ISLNK(buf.st_mode))
{
printf("symbolic link file \n");
//如果是符号链接文件时,试一下stat这个api
memset(&buf,0,sizeof(buf));
if(stat(argv[i],&buf) < 0)
{
continue;
}
printf("%s,stat : ino:%d,dev:%d,nlink:%d,uid: %d,gid:%d\n",argv[i],buf.st_ino,buf.st_dev,buf.st_nlink,buf.st_uid,buf.st_gid);
}
else
{
printf("unkown file\n");
}
}
return 0;
}
4、九种文件权限位
用户权限: S_IRUSR,S_IWUSR,S_IXUSR
组权限 : S_IRGRP, S_IWGRP, S_IXGRP
其他权限: S_IROTH, S_IWOTH, S_IXOTH
示例:
int fd = open("data.txt", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
也可以用八进制的方式
int fd = open("data.txt",O_WRONLY|O_CREAT, 0742);
7: 文件拥有者 4(r)+ 2 (w) + 1(x)
4: 同组人 4 (r)
2: 其他人 2 (w)
5、access
int access(const char *pathname,int mode);
pathname:文件路径
mode : 文件访问的权限
R_OK 判断是否有读权限
W_OK 判断是否有写权限
X_OK 判断是否有可执行权限(excute)
F_OK 判断是否存在
返回: 文件有mode权限返回0,其他返回-1
示例:
if(access("data.txt", R_OK|W_OK) == 0)
{
//文件有读写权限
}
else
{
// 文件没有读写权限
}