【发布时间】:2017-10-05 13:59:23
【问题描述】:
我一直在尝试使用函数将输出重定向到文件并从文件而不是标准输入中读取,但是当我重定向到文件并检查文件是否已被用输出创建,那里什么都没有。这个函数有什么问题。
/* Redirect a standard I/O file descriptor to a file
* Arguments: filename the file to/from which the standard I/O file
* descriptor should be redirected
* flags indicates whether the file should be opened for reading
* or writing
* destfd the standard I/O file descriptor which shall be
* redirected
* Returns: -1 on error, else destfd
*/
int redirect(char *filename, int flags, int destfd){
int ret;
if(flags == 0){
destfd = open(filename,O_RDONLY);
if (destfd < 0){
return -1;
}
ret = dup2(0,destfd);
if(ret < 0){
return -1;
}
close(destfd);
}
if(flags == 1){
destfd = open(filename,O_APPEND|O_WRONLY);
if (destfd < 0){
return -1;
}
ret = dup2(destfd,1);
if(ret < 0){
return -1;
}
close(destfd);
}
return destfd;
}
【问题讨论】:
-
为什么
destfd是函数的参数?
标签: c unix redirect pipe file-descriptor