简体   繁体   English

在UNIX中将文件从一个位置移动到另一个位置

[英]Move a file from a location to another in UNIX

I have to implement a shell in unix with some commands 我必须使用一些命令在UNIX中实现外壳

I want to move multiple files into a folder location like mv -t does. 我想将多个文件移动到mv -t一样的文件夹位置。

The problem is that rename function, just rename a file dont move that file. 问题在于重命名功能,仅重命名文件就不会移动该文件。

void mv_t()
{
  int mutat;
  char mvFile_name1[256];
  char mvFile_name2[256];
  int nr=0;

  printf("How many files you want to move: ");
  fflush(stdin);
  scanf("%d", &nr);

  printf("The file where you move: ");
  fflush(stdin);
  scanf("%s", &mvFile_name1);

  for(i=0; i<nr; i++)
  {
    printf("The file you want to move: ");
    fflush(stdin);
    scanf("%s", &mvFile_name2);

    mutat = rename(mvFile_name1, mvFile_name2);
    if(mutat != 0)
      perror("Error");
  }
}

This is what I wrote. 这就是我写的 In "for" he take mvFile_name1 and rename it as mvFile_name2, and then he don't have the previous name for the file. 在“ for”中,他使用mvFile_name1并将其重命名为mvFile_name2,然后他没有该文件的先前名称。 But if this will work, still don't move the files in the mvFile_name1, he just rename them like mvFile_name1. 但是,如果这行得通,仍然不要移动mvFile_name1中的文件,他只是将它们重命名为mvFile_name1。

You have your args to rename() in the wrong order, swap them. 您的args以错误的顺序rename() ,将它们交换。

They are: 他们是:

rename(oldpath, newpath);

Also you need to construct the newpath by striping off any path (part before a /) in the mvFile_name2 and replacing that with mvFile_name1. 另外,您还需要构造新路径,方法是剥离mvFile_name2中的任何路径(/之前的部分),然后将其替换为mvFile_name1。

Also you should verify that mvFile_name1 is a directory. 另外,您还应该验证mvFile_name1是一个目录。

So if the person enters: 因此,如果该人输入:

1
/tmp
/some/place/this.txt

then you should do: 那么您应该这样做:

rename(/some/place/this.txt, /tmp/this.txt);

Also if the oldpath and the newpath are on different disks, this will fail, but that may be more complication than you want to deal with. 同样,如果旧路径和新路径位于不同的磁盘上,这将失败,但是可能比您要处理的更为复杂。

Also, everything that @iharob said. 另外,@ iharob所说的一切。

Even if your code worked, it has some problems 即使您的代码有效,它也存在一些问题

  1. The fflush() function's behavior is not defined for input streams in the c standard, only for output. fflush()函数的行为未针对c标准中的输入流进行定义,仅针对输出进行了定义。 Thus, fflush(stdin) is undefined behavior. 因此, fflush(stdin)是未定义的行为。

  2. You must check scanf() 's return value, not doing so might cause problems specially for the "%d" specifier. 您必须检查scanf()的返回值,否则可能会导致专门针对"%d"说明符的问题。

  3. This scanf("%s", &mvFile_name1); 这个scanf("%s", &mvFile_name1); is wrong because mvFile_name1 is already a pointer to the first element of the array. 是错误的,因为mvFile_name1已经是指向数组第一个元素的指针。 Passing it's address is wrong because the resulting pointer has the wrong type. 传递它的地址是错误的,因为结果指针的类型错误。

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

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