系统编程中的文件描述符重定向和重命名dup/rename函数
思维导图
![这里写图片描述](https://img-blog.csdn.net/20161207224020999?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbHpqc3Fu/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
示例代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if(argc < 3)
{
printf("a.out oldName newName\n");
exit(1);
}
int ret = rename(argv[1], argv[2]);
if(ret == -1)
{
perror("rename");
exit(1);
}
return 0;
}
#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("test.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 = "你大爷的,我是个Gay!!!\n";
write(fd, buf, strlen(buf));
write(ret, buf1, strlen(buf1));
close(fd);
return 0;
}
int main()
{
int fd = open("test.txt", O_RDWR);
if(fd == -1)
{
perror("open");
exit(1);
}
int fd1 = open("fuck.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, "迎娶白富美!", 12);
close(fd);
close(fd1);
return 0;
}