Open原型
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *path, int flags, mode_t mode);
flags - 相互之间支持 | 操作:
O_TRUNC : 截断打卡
O_RDONLY : 只读打开
O_WRONLY : 只写打开
O_RDWR : 读写打开
O_APPEND : 每次写都加到文件尾端
O_CREAT : 若文件不存在则创建
mode - 操作权限,八进制,如 0666 等
lseek原型
#include <sys/types.h> //off_t
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence)
whence:
1. SEEK_SET, 文件偏移量 = 0 + offset;
2. SEEK_CUR, 文件偏移量 = 当前偏移量 + offset;
3. SEEK_END, 文件偏移量 = 文件长度 + offset;
注意,除非指定O_APPEND,否则打开文件的时候,偏移量会被设置为0; 对于普通文件,偏移量是非负值,但是设备文件等偏移量可以是负值。所以测试lseek返回值需要注意,要测试是否等于-1,不能测试是否小于0.
dup、dup2
#include <unistd.h>
int dup(int fd);
int dup2(int fd, int newfd);
1. 都是用来复制文件描述符;新的文件描述符跟旧文件描述符共享一个文件表项;
2. dup返回新的可用的最小文件描述符;
3. dup2返回指定的文件描述符newfd,如果newfd已经打开,则先关闭;
测试:
#include <stdio.h>
#include <unistd.h> /*read / write / close / dup ...*/
#include <fcntl.h> /*open*/
#include <errno.h>
#include <string.h>
#define MAXSIZE 100
int main(char argc, char **argv)
{
int fd, curpos, newpos, endpos;;
char buf[MAXSIZE] = {"This is my first test!\n"};
/* write text to the file */
if ( ((fd = open("./txt", O_RDWR | O_CREAT | O_TRUNC, 0666)) < 0))
perror("open error!\n");
if (write(fd, buf, strlen(buf)) != strlen(buf))
perror("write error!\n");
/* test lseek */
curpos = lseek(fd, 0, SEEK_CUR);
newpos = lseek(fd, 0, SEEK_SET);
endpos = lseek(fd, 10, SEEK_END);
printf(" !! curpos: %d; newpos: %d; endpos: %d\n", curpos, newpos, endpos);
memset(buf, 0, sizeof(buf));
strcpy(buf, "I will write this at the beginning!\n");
if (write(fd, buf, strlen(buf)) != strlen(buf))
perror("write error!\n");
/* we can use od the dump the txt file - */
printf("could you find the %d(endpos-curpos) holds?\n", (endpos - curpos));
system("od -c txt");
/* test dup & dup2*/
int preferfd = 10;
int newfd;
newfd = dup(fd);
dup2(fd, preferfd);
printf("\n fd %d\n", fd);
memset(buf, 0, sizeof(buf));
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
printf("%s\n", buf);
printf("\n newfd %d\n", newfd);
memset(buf, 0, sizeof(buf));
lseek(fd, 0, SEEK_SET);
read(newfd, buf, sizeof(buf));
printf("%s\n", buf);
printf("\n preferfd %d\n", preferfd);
memset(buf, 0, sizeof(buf));
lseek(fd, 0, SEEK_SET);
read(preferfd, buf, sizeof(buf));
printf("%s\n", buf);
close(fd);
close(newfd);
close(preferfd);
return 0;
}
测试结果:
!! curpos: 23; newpos: 0; endpos: 33
could you find the 10(endpos-curpos) holds?
0000000 T h i s i s m y f i r s t
0000020 t e s t ! \n \0 \0 \0 \0 \0 \0 \0 \0 \0
0000040 \0 I w i l l w r i t e t h
0000060 i s a t t h e b e g i n n
0000100 i n g ! \n
0000105
fd 3
This is my first test!
newfd 4
This is my first test!
preferfd 10
This is my first test!
注意:文件中是可以有“空洞”的