编程实现输出重定向:pwd >currentdif.
时间: 2023-08-11 18:04:10 浏览: 65
这是一个 shell 命令,可以通过使用系统提供的函数来实现。在 C 语言中,可以使用 `dup2()` 函数来实现输出重定向。
具体实现方法如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("currentdir", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
perror("open");
exit(1);
}
if (dup2(fd, STDOUT_FILENO) == -1) {
perror("dup2");
exit(1);
}
if (execlp("pwd", "pwd", NULL) == -1) {
perror("execlp");
exit(1);
}
return 0;
}
```
首先,使用 `open()` 函数打开文件 `currentdir`,并将其文件描述符保存到变量 `fd` 中。如果 `open()` 函数返回值为 `-1`,则说明打开文件失败,此时使用 `perror()` 函数输出错误信息,并退出程序。
接着,使用 `dup2()` 函数将标准输出的文件描述符 `STDOUT_FILENO` 重定向到文件 `currentdir` 中。如果 `dup2()` 函数返回值为 `-1`,则说明重定向失败,此时使用 `perror()` 函数输出错误信息,并退出程序。
最后,使用 `execlp()` 函数执行 `pwd` 命令。如果 `execlp()` 函数返回值为 `-1`,则说明执行命令失败,此时使用 `perror()` 函数输出错误信息,并退出程序。