几个系统函数
open
c
int open(const char *pathname, int flags, ...); //mode
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写
O_CREAT 若不存在创建
O_ APPEND 末尾添加
如果是有O_CREAT,最后参数是权限参数,否则忽略
S_IRWXU 0700 用户权限读写执行
close
c
int close(int fd);
例
c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int fd = open("test", O_RDONLY | O_CREAT, S_IRWXU);
printf("fd = %d\n", fd);
if (fd == -1)
printf("open failed\n");
close(fd);
return 0;
}
read
c
size_t read (int fd, void* buf, size_t cnt);
write
c
size_t write (int fd, void* buf, size_t cnt);
lseek
c
off_t lseek(int fd, off_t offset, int whence);
whence
SEEK_CUR 当前偏移 最后指向当前偏移+offset
SEEK_SET 把offset设为当前偏移
SEEK_END 指向结尾 可以用来获取文件大小
例
c
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd = open("test", O_RDONLY | O_CREAT,S_IRWXU);
printf("fd = %d\n", fd);
if (fd == -1)
printf("open failed\n");
char mem[256];
memset(mem,'a',256);
write(fd,mem,256);
lseek(fd,128,SEEK_SET);
memset(mem,0,256);
int res = read(fd,mem,256);
printf("res = %d\n", res);
int filesize = lseek(fd,0,SEEK_END);
printf("filesize = %d\n", filesize);
close(fd);
return 0;
}
输出
c
fd = 3
res = 128
filesize = 256