常见的文件和目录函数

来源:互联网 发布:nginx 访问权限控制 编辑:程序博客网 时间:2024/06/11 19:41

在APUE这本书,第三章与第四章都是在讲一些关于文件操作和目录操作的函数。简单地说明一下涉及到的函数及其使用。

  open函数

原型为: #include<fcntl.h>

  int open(const char *pathname, int oflag,.../*mode_t mode*/); 

      该函数是用来打开或创建一个文件(记住:是文件,不包括目录),第三个参数只有当打开文件不存在时(即open函数执行的是创建文件)才有用,mode_t是用来指定创建文件的用户ID,组ID,其他用户的读写权限的(注意:还有一个umask函数,真正权限是umask函数和参数mode联合决定的)。第二个参数表示怎么打开(以什么方式打开,读,写,读写等)。返回值为打开文件描述符。

creat函数

原型:#include<fcntl.h>

int creat(const char * pathnewname,mode_t mode);

     该函数用来创建一个文件。相当于:open(pathnewname,O_WRONLY|O_CREAT|O_TRUNC,mode). 从等价函数open中,可以看出creat函数特点:只能以写的形式打开该文件,当文件存在时,会将文件内容清除重新开始写。 返回值也是打开文件的描述符。

close函数

原型:#include<fcntl.h>

    int close(int filedes);

关闭函数,成功时返回0,失败则返回-1

lseek函数

原型:#include<unistd.h>

     int lseek(int filedes,off_t offset,int whence);

该函数用来显示地为打开一个文件设置偏移量。 

whence为seek_set时表示从起点开始,为seek_cur表示从当前位置还是,为seek_end表示从结尾出开始算。返回值为新的偏移量值。

该函数可以是文件形成空洞。

read函数

原型:#include<unistd.h>

    int read(int filedes,void * buf,int bufsize)

该函数用来读取文件的值。该函数读取文件的长度为bufsize,中途遇到空格或者是换行都不会停止的。

write函数

原型:#include<unitsd.h>

     int write(int filedes,void * buf,int bufsize)

该函数用来写文件

dup函数:

原型:#include<unisd.h>

    int dup(int filedes);   int dup2(int filedes,int filedes1);

该函数用来复制文件描述符。dup是从当前最小的描述符中找,dup2则是将其赋值到filedes1描述符中。最后是他们一起公用文件表项。

fcntl函数

原型:#include<fcntl.h>

     int fcntl(int filedes,int cmd,..../*int arg*/)

函数为改变已打开文件的性质。

stat函数

原型:#include<sys/stat.h>

    int stat(const char *restrict  pathname,struct stat* restrict buf);

    int fstat(int filedes,struct stat* restrict buf);

    int lstat(const char *restrict  pathname,struct stat* restrict buf);

该函数是返回与此命名的文件有关的信息结构,lstat是返回符号连接的相关信息,stats则是返回符号连接引用文件的信息

stat结构体信息如下:

struct stat {
mode_t  st_mode; /* file type & mode (permissions) */
ino_t  st_ino; /* i-node number (serial number) */
dev_t  st_dev; /* device number (file system) */
dev_t  st_rdev; /* device number for special files */
nlink_t  st_nlink; /* number of links */
uid_t  st_uid; /* user ID of owner */
gid_t  st_gid; /* group ID of owner */
off_t  st_size; /* size in bytes, for regular files */
struct timespec st_atim; /* time of last access */
struct timespec st_mtim; /* time of last modification */
struct timespec st_ctim; /* time of last file status change */
blksize_t  st_blksize; /* best I/O block size */
blkcnt_t  st_blocks; /* number of disk blocks allocated */
};

umask函数

原型;#include<sys/stat.h>

int umask(mode_t cmask);

该函数用来设置文件模式创建屏蔽字。返回原来的屏蔽字。








0 0