从0到1用代码入门C语言(八)

151 阅读2分钟

本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路。

十六、扩展部分

access库函数用来判断当前操作系统用户对文件或者目录的权限,#include <unistd.h>函数声明int access(const char *pathname,int mode);pathname文件名或目录名,mode 需要判断的存取权限。在头文件unistd.h中的预定义如下:

#define R_OK 4     // R_OK 只判断是否有读权限
#define W_OK 2    // W_OK 只判断是否有写权限
#define X_OK 1     // X_OK 判断是否有执行权限
#define F_OK 0     // F_OK 只判断是否存在

struct stat结构体用于存放文件和目录的状态信息:

struct stat
{
  dev_t st_dev;   // device 文件的设备编号
  ino_t st_ino;   // inode 文件的i-node
  mode_t st_mode;   // protection 文件的类型和存取的权限
  nlink_t st_nlink;   // number of hard links 连到该文件的硬连接数目, 刚建立的文件值为1.
  uid_t st_uid;   // user ID of owner 文件所有者的用户识别码
  gid_t st_gid;   // group ID of owner 文件所有者的组识别码
  dev_t st_rdev;  // device type 若此文件为设备文件, 则为其设备编号
  off_t st_size;  // total size, in bytes 文件大小, 以字节计算
  unsigned long st_blksize;  // blocksize for filesystem I/O 文件系统的I/O 缓冲区大小.
  unsigned long st_blocks;  // number of blocks allocated 占用文件区块的个数, 每一区块大小为512 个字节.
  time_t st_atime;  // time of lastaccess 文件最近一次被存取或被执行的时间, 一般只有在用mknod、 utime、read、write 与tructate 时改变.
  time_t st_mtime;  // time of last modification 文件最后一次被修改的时间, 一般只有在用mknod、 utime 和write 时才会改变
  time_t st_ctime;  // time of last change i-node 最近一次被更改的时间, 此参数会在文件所有者、组、 权限被更改时更新
};

st_mode成员的取值很多,或者使用如下两个宏来判断。

 S_ISREG(st_mode)  // 是否为一般文件 
 S_ISDIR(st_mode)  // 是否为目录

stat库函数,包含头文件:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

函数声明:

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

stat函数获取path指定文件或目录的信息,并将信息保存到结构体buf中,执行成功返回0,失败返回-1。

用于修改文件存取时间和更改时间的函数:utime

#include <utime.h>

utime()用来修改参数filename 文件所属的inode 存取时间。如果参数times为空指针(NULL), 则该文件的存取时间和更改时间全部会设为目前时间。结构utimbuf 定义如下:

struct utimbuf
{
  time_t actime;
  time_t modtime;
};

返回值:执行成功则返回0,失败返回-1。

rename函数:重命名文件或目录

#include <stdio.h>
int rename(const char *oldpath, const char *newpath);

oldpath 文件或目录的原名。

newpath 文件或目录的新的名称。

返回值:0-成功,-1-失败。

remove函数用于删除文件或目录,相当于操作系统的rm命令。

#include <stdio.h>
int remove(const char *pathname);

pathname 待删除的文件或目录名。

返回值:0-成功,-1-失败。