一、目录和文件
在当前目录下使用touch 创建一个名为 -a的文件:
touch -a ; // 错误,
touch -- -a//正确
touch ./-a 正确
ls -n可以看到对象的用户id,可以在/etc/passwd中查看,/etc/group可以看到组号
获取文件属性
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *pathname, struct stat *statbuf);
int fstat(int fd, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);
#include <fcntl.h> /* Definition of AT_* constants */
#include <sys/stat.h>
int fstatat(int dirfd, const char *pathname, struct stat *statbuf,
int flags);
struct stat {
dev_t st_dev; /* ID of device containing file */ 包含这个文件的设备ID号
ino_t st_ino; /* Inode number */ ls -i可以看到inode号
mode_t st_mode; /* File type and mode */ 权限信息(16位)
nlink_t st_nlink; /* Number of hard links */ 硬链接数
uid_t st_uid; /* User ID of owner */ 用户id
gid_t st_gid; /* Group ID of owner */ 组id
dev_t st_rdev; /* Device ID (if special file) */ 设备的ID号
off_t st_size; /* Total size, in bytes */ 字节数
blksize_t st_blksize; /* Block size for filesystem I/O */ 块大小,一般512B
blkcnt_t st_blocks; /* Number of 512B blocks allocated */ 占的块数 快数/2为所栈磁盘空间的大小。/* Since Linux 2.6, the kernel supports nanosecond
precision for the following timestamp fields.
For the details before Linux 2.6, see NOTES. */struct timespec st_atim; /* Time of last access */ 上次访问时间
struct timespec st_mtim; /* Time of last modification */上次修改时间
struct timespec st_ctim; /* Time of last status change */上次改变时间#define st_atime st_atim.tv_sec /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};stat命令也可以查看信息
stat
将文件属性信息填入statbuf结构体,成功返回0.失败返回-1
fstat
传入文件描述符整形
lstat
传入链接文件
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
static off_t flen(const char *file)
{
struct stat st;
if(stat(file,&st)<0 )
{
perror("stat()");
exit(-1);
}
return st.st_size;
}
int main(int argc,char *argv[])
{
if(argc <2)
return -1;
off_t len = flen(argv[1]);
printf("%lld \n",(long long)len);
return 0;
}
空洞文件
占用字节size大小,但是在linux下不占用磁盘空间,磁盘空间占用有:块大小*块总数。stat命令查看。
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,char *argv[] )
{
if(argc <2)
return -1;
int fd;
fd = open(argv[1],O_WRONLY|O_CREAT|O_TRUNC,0600);
if(fd<0)
{
perror("open()");
return -1;
}
// lseek(fd,5*1,SEEK_SET);
lseek(fd,5LL*1024LL*1024LL*1024LL-1LL,SEEK_SET);//数字添加LL,防止计算过程中精度溢出
write(fd,"",1);//发生一次系统调用,否则不占用空间
close(fd);
return 0;
}
文件访问权限
st_mode是一个16位的位图,用于表示文件的类型,文件访问权限及特殊的权限位,参考man手册:man 2 stat
umask
使用命令:umask 可以设置 默认是 0002
umask 0022
作用:防止产生权限过松的文件
文件权限管理
chmod
chmod命令更改文件的权限:chmod 777 temp.file 也可以使用 chmod a+x temp.file
chmod函数:int chmod(c