C 将内容从一个文件复制到另一个文件
在linux平台(ubuntu)上用c编写一个程序,将内容从一个文件复制到另一个文件,或者创建一个程序,在ubuntu中复制文件C 将内容从一个文件复制到另一个文件,c,command,cp,C,Command,Cp,在linux平台(ubuntu)上用c编写一个程序,将内容从一个文件复制到另一个文件,或者创建一个程序,在ubuntu中复制文件 使用打开一个文件 使用fopen打开第二个文件 使用从第一个文件读取 写入第二个文件使用 如果需要编写格式化数据,可以用fread和fwrite代替 您没有指定必须使用什么编程语言。所以,我假设您使用的是bash。编写一个使用cp命令的脚本,您的任务就解决了。我会像使用Shell一样使用重定向和管道?下面的示例来自我编写的一个shell,这就是重定向函数。(>>)
- 使用打开一个文件
- 使用fopen打开第二个文件
- 使用从第一个文件读取
- 写入第二个文件使用
- 如果需要编写格式化数据,可以用fread和fwrite代替
- 您没有指定必须使用什么编程语言。所以,我假设您使用的是bash。编写一个使用
cp
命令的脚本,您的任务就解决了。我会像使用Shell一样使用重定向和管道?下面的示例来自我编写的一个shell,这就是重定向函数。(>>)
因此,您可以执行file1>>file2,它会将一个文件的内容复制到另一个文件。
)//写入文件是重要的部分
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]);
}
}
这听起来像是家庭作业。如果是这样的话,我们不赞成这里的人。我们会在具体问题上提供帮助,但我们不会为您提供帮助。如果不是,请对你的问题更具体一点……而不仅仅是“请为我写这封信。”好吧——我已经写了……现在怎么办?您的尝试在哪里遇到问题?对于文件复制,您不会替换scanf()和printf(),因为数据没有格式化。这取决于赋值的具体内容,但这就是为什么我将它们作为替代品“编写一个程序,用c…将内容从一个文件复制到另一个文件”。“问题”(如果你想这样称呼它)也被标记为C.我的错误。下次我会更小心的。而且“C”标签很窄;-)我承认这一点。是个鬼鬼祟祟的小家伙。
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]);
}
}