简体   繁体   中英

Move a file from a location to another in UNIX

I have to implement a shell in unix with some commands

I want to move multiple files into a folder location like mv -t does.

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. But if this will work, still don't move the files in the mvFile_name1, he just rename them like mvFile_name1.

You have your args to rename() in the wrong order, swap them.

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.

Also you should verify that mvFile_name1 is a directory.

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.

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. Thus, fflush(stdin) is undefined behavior.

  2. You must check scanf() 's return value, not doing so might cause problems specially for the "%d" specifier.

  3. This scanf("%s", &mvFile_name1); is wrong because mvFile_name1 is already a pointer to the first element of the array. Passing it's address is wrong because the resulting pointer has the wrong type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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