- 论坛徽章:
- 0
|
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <error.h>
#include <sys/stat.h>
#include <sys/types.h>
int my_dup2(int oldfd, int newfd)
{
int i, fd[newfd>oldfd?newfdldfd], fd2;
/* newfd is equal oldfd then we do nothing just return */
if (newfd == oldfd)
return newfd;
/* close newfd whether newfd is a real fd */
close(newfd);
for (i = 0; (fd = dup(oldfd)) != newfd; i++) ;
fd2 = fd;
for (i--; i >= 0; i--) close(fd);
return fd2;
}
int main(void)
{
int fd, fd2 ,i;
char string[] ="adfasfasDF";
char buf[1024]={'\0'};
struct stat statbuf;
fd = open("tmpfile", O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR);
if(fd == -1)
{
perror("error"
exit(1);
}
i = write(fd,string,sizeof(string));
if(i == -1)
{
perror("werror"
exit(1);
}
fd2 = fd +3;
i= my_dup2(fd,fd2);
lseek(fd2,-sizeof(string), 1);
i=read(fd2, buf, sizeof(string));
printf("buf1: %s\n", buf);
return 0;
} |
|