gpt4 book ai didi

将一个文件的内容复制到另一个文件

转载 作者:行者123 更新时间:2023-11-30 16:03:30 25 4
gpt4 key购买 nike

在linux平台(ubuntu)上用c编写一个程序,将一个文件的内容复制到另一个文件,或者创建一个在ubuntu中复制文件的程序

最佳答案

我会考虑使用重定向和管道,就像使用 Shell 一样?下面的示例来 self 编写的 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]);
}
}

关于将一个文件的内容复制到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4069536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com