您的位置:首页 > 运维架构 > Linux

linux系统文件操作函数之dup,dup2,fcntl

2018-04-03 19:44 639 查看
1

int dup(int fd);

int dup2(int fd1,int fd2);

两个均为复制一个现存的文件的描述

头文件:unistd.h

两个函数的返回:若成功为新的文件描述,若出错为-1;

由dup返回的新文件描述符一定是当前可用文件描述中的最小数值。

用dup2则可以用fd2参数指定新的描述符数值。如果fd2已经打开,则先关闭。若fd1=fd2,则dup2返回fd2,而不关闭它。通常使用这两个系统调用来重定向一个打开的文件描述符。

案例:dup.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("a.txt", O_RDWR);
if(fd == -1)
{
perror("open");
exit(1);
}
printf("file open fd = %d\n", fd);
// 找到进程文件描述表中 ==第一个== 可用的文件描述符
// 将参数指定的文件复制到该描述符后,返回这个描述符
int ret = dup(fd);
if(ret == -1)
{
perror("dup");
exit(1);
}
printf("dup fd = %d\n", ret);
char* buf = "你是猴子派来的救兵吗????\n";
char* buf1 = "你大爷的,我是程序猿!!!\n";
write(fd, buf, strlen(buf));
write(ret, buf1, strlen(buf1));

close(fd);
return 0;


}

案例:dup2.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("english.txt", O_RDWR);
if(fd == -1)
{
perror("open");
exit(1);
}
int fd1 = open("a.txt", O_RDWR);
if(fd1 == -1)
{
perror("open");
exit(1);
}
printf("fd = %d\n", fd);
printf("fd1 = %d\n", fd1);
int ret = dup2(fd1, fd);
if(ret == -1)
{
perror("dup2");
exit(1);
}
printf("current fd = %d\n", ret);
char* buf = "主要看气质 ^_^!!!!!!!!!!\n";
write(fd, buf, strlen(buf));
write(fd1, "hello, world!", 13);
close(fd);
close(fd1);
return 0;
}


2 fcntl函数,fcntl是计算机中的一种函数,通过fcntl可以改变已打开的文件性质

头文件

#include <sys/types.h>
#include <unistd.h>
#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);

fcntl()针对(文件)描述符提供控制.参数fd 是被参数cmd操作(如下面的描述)的描述符.针对cmd的值,fcntl能够接受第三个参数int arg

案例3:fcntl.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
int fd;
int flag;
// 测试字符串
char *p = "我们是一个有中国特色的社会主义国家!!!!!!";
char *q = "呵呵, 社会主义好哇。。。。。。";
// 只写的方式打开文件
fd = open("test.txt", O_WRONLY);
if(fd == -1)
{
perror("open");
exit(1);
}
// 输入新的内容,该部分会覆盖原来旧的内容
if(write(fd, p, strlen(p)) == -1)
{
perror("write");
exit(1);
}
// 使用 F_GETFL 命令得到文件状态标志
flag = fcntl(fd, F_GETFL, 0);
if(flag == -1)
{
perror("fcntl");
exit(1);
}
// 将文件状态标志添加 ”追加写“ 选项
flag |= O_APPEND;
// 将文件状态修改为追加写
if(fcntl(fd, F_SETFL, flag) == -1)
{
perror("fcntl -- append write");
exit(1);
}
// 再次输入新内容,该内容会追加到旧内容的后面
if(write(fd, q, strlen(q)) == -1)
{
perror("write again");
exit(1);
}
// 关闭文件
close(fd);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: