函数原型:
#include
int dup(int oldfd);
int dup2(int oldfd,int newfd);
dup用来复制oldfd所指的文件描述符。但复制成功时返回最小的尚未被使用的文件描述符。若有错误则返回-1,错误代码存入errno中。返回的新文件描述符和参数oldfd指向同一个文件,共享所有的锁定,读写指针,和各项权限或标志位。
1.打开一个新文件
2.关掉标准输出文件符
3.调用dup给文件描述符
4.此时文件描述符变为1
5.将所要打印数据重定向到文件中
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#define _PATH_FILE_ "./log"
int main()
{
umask(0);
int fd=open(_PATH_FILE_,O_CREAT|O_RDWR,0644);
if(fd<0){
perror("open");
return 1;
}
close(1);
int new_fd=dup(fd);
close(fd);
int count=0;
while(count++<100)
{
printf("helo world\n");
}
fflush(stdout);//must,printf重定向后变为全缓冲,缓冲区满才会刷新,导致不会写入文件
close(new_fd);
return 0;
}
dup2
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#define _FILE_ "./log"
int main()
{
umask(0);
int fd=open(_FILE_,O_CREAT|O_WRONLY,0644);
if(fd<0){
perror("open");
return 1;
}
close(1);//isn't necessary
int ret=dup2(fd,1);
if(ret<0){
perror("dup2");
return 2;
}
char buf[1024];
while(1)
{
memset(buf,'\0',sizeof(buf));
fgets(buf,sizeof(buf)-1,stdin);//stdin是FILE*,0是文件描述符
if(strncmp(buf,"quit",4)==0)//buf have '\n',you can buf[_s-1]='\0'
break;
printf("hello:%s",buf);
}
close(fd);
return 0;
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。