0

Linuxプラットフォーム(ubuntu)のcで、あるファイルから別のファイルにコンテンツをコピーするプログラムを作成するか、ubuntuでファイルのコピーを作成するプログラムを作成します

4

3 に答える 3

1

シェルのようにリダイレクトとパイプを使用することを検討しますか? 以下の例は私が書いたシェルからのもので、これは具体的にはリダイレクト機能です。(>>) 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]);
  }
}
于 2010-11-01T16:10:18.807 に答える
0

一般的なアイデア

  • fopenを使用して 1 つのファイルを開く
  • fopen を使用して 2 番目のファイルを開く
  • freadを使用して最初のファイルから読み取る
  • fwriteを使用して 2 番目のファイルに書き込む

  • フォーマットされたデータを書き込む必要がある場合は、fread をscanfに、fwrite をfprintfに置き換えることができます。

于 2010-11-01T14:10:59.800 に答える
0

どのプログラミング言語を使用する必要があるかを指定していません。したがって、bash を使用していると仮定します。コマンドを使用するスクリプトを作成するcpと、課題が解決されます。

于 2010-11-01T14:14:39.397 に答える