Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Linux中使用C将单个文件复制到不同的分区_C_Linux_Copy_Move_Disk Partitioning - Fatal编程技术网

如何在Linux中使用C将单个文件复制到不同的分区

如何在Linux中使用C将单个文件复制到不同的分区,c,linux,copy,move,disk-partitioning,C,Linux,Copy,Move,Disk Partitioning,重命名(),链接()不起作用 谢谢 rename()应该可以工作。你检查过它返回的错误了吗?根据文档,如果重命名成功,则返回0: 您可以使用peror()将错误字符串打印为标准错误(stderr,通常是屏幕): 您是否尝试过使用标准的旧C函数 `fopen` the source on one partition `fopen` the destination on the other partition LOOP while `fread` > 0 `fread` from t

重命名(),链接()不起作用

谢谢

rename()应该可以工作。你检查过它返回的错误了吗?根据文档,如果重命名成功,则返回0:

您可以使用peror()将错误字符串打印为标准错误(stderr,通常是屏幕):


您是否尝试过使用标准的旧C函数

`fopen` the source on one partition
`fopen` the destination on the other partition

LOOP while `fread` > 0
   `fread` from the source to a buff
   `fwrite` to the dest from a buff
然后关闭您的文件(例如,
fclose

这也更便于携带


编辑:如果你想让它变得非常基本,为什么不使用脚本语言(python/bash)并在几行代码中完成呢。

我就是这样做的。它非常简单,将实际复制的棘手部分留给
cp
工具,该工具已成功完成此任务数年

#include <assert.h>
#include <string.h>

#include <sys/wait.h>
#include <unistd.h>

int
runvp(int *ret_status, const char *command, const char * const *argv)
{
  pid_t pid;
  int status;
  char * const *execv_argv;

  pid = fork();
  if (pid == (pid_t) -1)
    return -1;

  if (pid == 0) {
    /*
     * Circumvent the C type conversion rules;
     * see ISO C99: 6.5.16.1#6 for details.
     */
    assert(sizeof(execv_argv) == sizeof(argv));
    memcpy(&execv_argv, &argv, sizeof(execv_argv));

    (void) execvp(command, execv_argv);
    return -1;
  }

  if (waitpid(pid, &status, 0) == -1)
    return -1;

  *ret_status = status;
  return 0;
}

fopen
+
fread
+
fwrite
+
fclose
。不同的分区意味着您必须复制。这不是个好主意。如果
cp
遇到错误,您将无法判断出哪里出了问题,而且在这个过程中,它会向stderr吐出一些东西,再加上它会拾取路径中发生的任何“cp”(即潜在的安全漏洞),再加上它比只编写自己的复制函数更长、更复杂。使用类似于“这也更具可移植性”——有点像。开始实施“可移植文件拷贝”的问题“不同的系统具有不同的文件元数据,从文件权限开始,依次是访问时间、所有权、ACL和额外的数据流。因此,生成的副本是可移植的,但它所做的并不一定非常有用,因为它不复制任何明智的用户认为的“文件”,只复制文件内容。
cp--preserve
的源代码应该让您了解您可能还想复制什么,这就是为什么我将“more”斜体化,并建议使用Python或bash中的复制函数,而不是使用C函数复制文件内容。
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  int exitcode;
  const char *cmdline[] = {
    "cp",
    "--",
    argv[1],
    argv[2],
    NULL
  };

  if (runvp(&exitcode, cmdline[0], cmdline) == -1) {
    perror("runvp");
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}