文件相关操作

一、判断文件是否存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
inline bool exists_test0 (const std::string& name) {
// 以 ifstream 打开文件流,成功则存在,失败则不存在
ifstream f(name.c_str());
return f.good();
}

inline bool exists_test1 (const std::string& name) {
// 以 fopen 读方式打开文件,成功则存在,失败则不存在
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}

inline bool exists_test2 (const std::string& name) {
// 以 access 函数获取文件状态,成功则存在,失败则不存在
return ( access( name.c_str(), F_OK ) != -1 );
}

inline bool exists_test3 (const std::string& name) {
// 使用 stat 函数获取文件状态,成功则存在,失败则不存在
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}

性能测试对比结果:stat 函数的方式性能最好

1
2
3
4
5
6
# Results for total time to run the 100,000 calls averaged over 5 runs,

Method exists_test0 (ifstream): **0.485s**
Method exists_test1 (FILE fopen): **0.302s**
Method exists_test2 (posix access()): **0.202s**
Method exists_test3 (posix stat()): **0.134s**

二、获取文件权限

linux 中 struct stat 结构体中定义了文件的相关属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct stat {
mode_t st_mode; //文件对应的模式,文件,目录等
ino_t st_ino; //inode节点号
dev_t st_dev; //设备号码
dev_t st_rdev; //特殊设备号码
nlink_t st_nlink; //文件的连接数
uid_t st_uid; //文件所有者
gid_t st_gid; //文件所有者对应的组
off_t st_size; //普通文件,对应的文件字节数
time_t st_atime; //文件最后被访问的时间
time_t st_mtime; //文件内容最后被修改的时间
time_t st_ctime; //文件状态改变时间
blksize_t st_blksize; //文件内容对应的块大小
blkcnt_t st_blocks; //伟建内容对应的块数量
};

其中 stat 结构体中的 st_mode 则定义了下列情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
S_IFMT   0170000    文件类型的位遮罩
S_IFSOCK 0140000 scoket
S_IFLNK 0120000 符号连接
S_IFREG 0100000 一般文件
S_IFBLK 0060000 区块装置
S_IFDIR 0040000 目录
S_IFCHR 0020000 字符装置
S_IFIFO 0010000 先进先出

S_ISUID 04000 文件的(set user-id on execution)位
S_ISGID 02000 文件的(set group-id on execution)位
S_ISVTX 01000 文件的sticky位

S_IRUSR(S_IREAD) 00400 文件所有者具可读取权限
S_IWUSR(S_IWRITE)00200 文件所有者具可写入权限
S_IXUSR(S_IEXEC) 00100 文件所有者具可执行权限

S_IRGRP 00040 用户组具可读取权限
S_IWGRP 00020 用户组具可写入权限
S_IXGRP 00010 用户组具可执行权限

S_IROTH 00004 其他用户具可读取权限
S_IWOTH 00002 其他用户具可写入权限
S_IXOTH 00001 其他用户具可执行权限

获取文件权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#define N_BITS 3
int main(int argc, char* argv[]) {
unsigned int i, mask=0700;
struct stat buff;
static char *perm[]={"---","--x","-w-","-wx","r--","r-x","rw-","rwx"};
if(argc>1) {
if((stat(argv[1], &buff)!=-1)) {
printf("permissions for %s\t",argv[1]);
for(i=3;i;--i) {
printf("%3s",perm[(buff.st_mode&mask)>>(i-1)*N_BITS]);
mask>>=N_BITS;
}
putchar('\n');
}
else {
perror(argv[1]);
exit(1);
}
}
}

通过 access 函数判断文件是否存在、可读、可写、可执行:https://blog.csdn.net/songyulong8888/article/details/80719225