OPEN(2) System calls
open, creat - open and possibly create a file or device
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
open系统调用就是打开一个文件,也就是把一个pathname转化成一个文件描述符。
flags参数:
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写
O_CREAT 创建文件
O_EXCL 与O_CREAT连用,如果文件已经存在,则强制open失败。
O_TRUNC 如果要打开的文件是个常规文件,并且已经存在,可写,则文件长度为0.
close - close a file descriptor
#include <unistd.h>
int close(int fd);
read 用于从文件描述符对应的文件中读取数据
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
试图读取count个字节的数据到buf中。
write向文件中写数据
#include <unistd.h>
ssize_t write(int fd,const void *buf,size_t count);
ftruncate 缩短文件的长度。
#include <unistd.h>
int ftruncate(int fd, off_t length);
int truncate(const char* path, off_t length);
lseek文件定位
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
whence可以是
SEEK_CUR: 当前位置;SEEK_SET:直接设置;SEEK_END:最后位置。
fsync将所有已经写入的数据真正写到设备上。
#include <unistd.h>
int fsync(int fd);
int fdatasync(int fd); 只写数据,不写元数据,例如mtime,atime.
fstat获取文件信息
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *file_name,struct stat *buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *file_name,struct stat *buf);
struct stat
{
dev_t st_dev; // device
ino_t st_ino; // inode
mode_t st_mode; // protection
nlink_t st_nlink; // number of hard links
uid_t st_uid; // user ID of owner
gid_t st_gid; // group ID of owner
dev_t st_rdev; // device type (if inode device)
off_t st_siez; // total size, in bytes
unsigned long st_blksize; // blocksize for filesystem I/O
unsigned long st_blocks; // number of blocks allocated
time_t st_atime; // time of last access
time_t st_mtime; // time of last modification
time_t st_ctime; // time of last change.
};
MKSTEMP(3)
mkstemp - create a unique temporary file
#include <stdlib.h>
int mkstemp(char *template);
生成一个唯一的临时文件,临时文件的名字来自模板template,最后6个字符必须是XXXXXX,这6个字符会被替换以保证文件名的唯一性。
fchown改变文件所有权
#include <sys/types.h>
#include <unistd.h>
int chown(const char *path,uid_t owner,gid_t group);
int fchown(int fd, uid_t owner, gid_t group);
int lchown(const char *path, uid_t owner, gid_t group);
fchmod改变文件读写权
#include <sys/types.h>
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
int fchmod(int fildes, mode_t mode);
flock申请或删除一个文件的建议性锁。
#include <sys/file.h>
int flock(int fd, int operation);
operation:
LOCK_SH: 放上共享锁
LOCK_EX: 排斥锁
LOCK_UN: 解锁
fcntl操作一个文件操述符。
#include <fcntl.h>
int fcntl(int fd, int cmd);
int fcntl(int fd, int cmd, long arg);
int fcntl(int fd, int cmd, struct flock *lock);
F_DUPFD: 复制文件描述符fd
F_GETFD: 获得fd的close-on-exec标志
F_SETFD: 设置close-on-exec标志
F_GETFL: 得到open设置的标志
F_SETFL
F_GETLK: 得到文件锁
dup dup2复制文件描述符,dup2可以让用户指定返回的文件描述符的值。
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);