简体   繁体   English

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

[英]Copies contents from one file to another

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

I would look into using redirection and pipes like you would with a Shell? 我会像使用Shell一样研究使用重定向和管道吗? this example below was from a shell I wrote, this is specifically the redirect function. 下面的示例来自我编写的shell,这是重定向功能。 (>>) so you could do file1 >> file2 and it would copy the contents of one file to another. (>>),因此您可以执行file1 >> file2,它将把一个文件的内容复制到另一个文件。 the

open(file[0], O_RDWR | O_CREAT, 0666); and while ((count = read(0, &c, 1)) > 0)
          write(fd, &c, 1)

; ; //Write to file are the important parts //写入文件是重要的部分

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]);
  }
}

The General IDEA 通用IDEA

  • Open one file using fopen 使用fopen打开一个文件
  • Open a Second File using fopen 使用fopen打开第二个文件
  • Read from the first file using fread 使用fread从第一个文件读取
  • Write to the Second File use fwrite 使用fwrite写入第二个文件

  • You can substitute scanf for fread and, fprintf for fwrite if you need to write formated data. 如果需要写入格式化的数据,则可以用scanf代替fread,用fprintf代替fwrite。

You didn't specify what programming language must be used. 您没有指定必须使用哪种编程语言。 So, I'll assume you're using bash. 因此,我假设您正在使用bash。 Write a script that uses the cp command and your assignment is solved. 编写一个使用cp命令的脚本,您的分配就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM