#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void fcntl_dup_fd(void)
{
int fd = open("temp", O_RDWR | O_CREAT, 0664);
if(fd == -1)
{
perror("open");
exit(1);
}
// 复制文件描述符
// int fd1 = dup(fd);
int fd1 = fcntl(fd, F_DUPFD, 0);
// 写文件
char *p = "hello, world!!";
write(fd1, p, strlen(p)+1);
close(fd1);
// 读文件
char buf[64] = { 0 };
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
printf("buf = %s\n", buf);
close(fd);
}
int fcntl_getfg_setfg(void)
{
int fd = open("temp1", O_RDWR | O_CREAT, 0664);
if(fd == -1)
{
perror("open");
exit(1);
}
// 获取文件的flags
int flags = fcntl(fd, F_GETFL, 0);
// 写文件
char *p = "hello, world!!";
write(fd, p, strlen(p)+1);
// 文件flags追加属性 O_APPEND
flags = flags | O_APPEND;
// 设置新的flags属性
fcntl(fd, F_SETFL, flags);
// 写文件
p = "aaaaaaaaaaaaaaaaaaaaaaaaa";
write(fd, p, strlen(p)+1);
close(fd);
return 0;
}
int main(int argc, const char *argv[])
{
int ret = -1;
fcntl_dup_fd();
puts("-------------------");
fcntl_getfg_setfg();
}
测试结果

版权声明:本文为zxy131072原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。