我会考虑使用重定向和管道,就像使用 Shell 一样?下面的这个例子来自我写的一个shell,这就是重定向功能。 (>>)
所以你可以做 file1 >> file2 它将一个文件的内容复制到另一个文件。
open(file[0], O_RDWR | O_CREAT, 0666); and while ((count = read(0, &c, 1)) > 0)
write(fd, &c, 1)
; //写入文件是重要的部分
void redirect_cmd(char** cmd, char** file) {
int fds[2]; // file descriptors
int count; // used for reading from stdout
int fd; // single file descriptor
char c; // used for writing and reading a character at a time
pid_t pid; // will hold process ID; used with fork()
pipe(fds);
if (fork() == 0) {
fd = open(file[0], O_RDWR | O_CREAT, 0666);
dup2(fds[0], 0);
close(fds[1]);
// Read from stdout
while ((count = read(0, &c, 1)) > 0)
write(fd, &c, 1); //Write to file
exit(0);
//Child1
} else if ((pid = fork()) == 0) {
dup2(fds[1], 1);
//Close STDIN
close(fds[0]);
//Output contents
execvp(cmd[0], cmd);
perror("execvp failed");
//Parent
} else {
waitpid(pid, NULL, 0);
close(fds[0]);
close(fds[1]);
}
}