系统调用接口
1.open - 打开/创建文件
2.creat - 创建空文件
3.close - 关闭文件
4.read - 读取文件
5.write - 写入文件
6.lseek - 设置读写位置
7.fcntl - 修改文件属性
8.unlink - 删除硬链接
9.rmdir - 删除空目录
10.remove - 删除硬链接(unlink)或空目录(rmdir)
open
#include <fcntl.h>
int open (
const char* pathname,
int flags,
mode_t mode
);
int open (
const char* pathname,
int flags
);
create
#include <fcntl.h>
int creat (
const char* pathname,
mode_t mode
);
flags为以下值的位或:
O_RDONLY - 只读。
O_WRONLY - 只写。
O_RDWR - 读写。
O_APPEND - 追加。
O_CREAT - 创建,不存在即创建(已存在即直接打开,
并保留原内容,除非...),
有此位mode参数才有效。
O_EXCL - 排斥,已存在即失败。
O_TRUNC - 清空,已存在即清空
(有O_WRONLY/O_RDWR)。
O_NOCTTY - 非控,若pathname指向控制终端,
则不将该终端作为控制终端。
O_NONBLOCK - 非阻,若pathname指向FIFO/块/字符文件,
则该文件的打开及后续操作均为非阻塞模式。
O_SYNC - 同步,write等待数据和属性,
被物理地写入底层硬件后再返回。
O_DSYNC - 数同,write等待数据,
被物理地写入底层硬件后再返回。
O_RSYNC - 读同,read等待对所访问区域的所有写操作,
全部完成后再读取并返回。
O_ASYNC - 异步,当文件描述符可读/写时,
向调用进程发送SIGIO信号
close
#include <unistd.h>
int close (
int fd
);
lseek
lseek函数的作用是将文件位置记录,不会对文件产生实际影响和改变。
#include <sys/types.h>
#include <unistd.h>
off_t lseek (
int fd,
off_t offset,
int whence
);
成功返回当前文件位置,失败返回-1。
whence取值:
SEEK_SET - 从文件头
(文件的第一个字节)。
SEEK_CUR - 从当前位置
(上一次读写的最后一个字节的下一个位置)。
SEEK_END - 从文件尾
(文件的最后一个字节的下一个位置)。
例子
模拟拷贝文件
#include <stdio.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int copy(const char *srcFileName,const char *destFileName){
int sfd = open(srcFileName,O_RDONLY);
if(sfd == -1){
printf("%s\n",strerror(errno));
return -1;
}
int dfd = open(destFileName,O_WRONLY|O_CREAT|O_EXCL,0644);
if(dfd == -1){
if(errno == EEXIST){
printf("%s 文件存在!\n",destFileName);
}else{
printf("%s\n",strerror(errno));
}
close(sfd);
return -1;
}
char str[128] = {};
ssize_t ret;
while((ret = read(sfd,str,128))>0){
write(dfd,str,ret);
}
close(sfd);
close(dfd);
return 0;
}
int main(int argc,char *argv[]){
if(argc < 3){
printf("%s srcfile destfile\n",argv[0]);
return -1;
}
copy(argv[1],argv[2]);
return 0;
}