Question

When I try to rename a file from a cifs mount to a local path (moving the file from server to local hdd), I get a -1. I can remove the file, and I can add new files, I just can't use the rename() function to do it. The program is being ran as root and the user in the cifs mount has full rights to the share and to the local filesystem on the server.

Server: Windows XP SP3 x32

Local: Ubuntu 13.04 x64

smb mount:

sudo mount -t cifs -o username=admin_account,password=<passw> \
  //server/share /local/mount/point

C code:

void
function moveFile(char *fname){
  char *base;
  base = basename(fname);
  char newF[strlen(getSaveDir()) + strlen(base)];
  sprintf(newF,"%s%s", getSaveDir(), base);
  int result;
  result = rename(fname, newF);
  if( result == 0 ) {
    printf("Moved file: %s to %s", fname, newF);
  } else {
    printf("There was an error moving %s to %s (ID: %d)", fname, newF, result);
    //TODO figure out better fix than this
    remove(fname);
  }
}
Was it helpful?

Solution

rename() only works on the same device, it just changes its name(or "moves" the name to another directory). rename() cannot move the file data from one location to another.

If you want to copy or move the file, you need to do it yourself:

  • open the source and destination file
  • read() from the source file, write to the destination file in a loop until the end.
  • unlink() the source file (only if you want to move it.)

OTHER TIPS

In all likelihood, if you interrogate errno after rename fails, you will find that it is set to EXDEV.

May I suggest that you add that information or confirm that it is EXDEV.

If you are getting EXDEV, then it is because of the Linux limitation that rename() only works if oldpath and newpath are on the same mounted file system.

From rename(2)

   EXDEV  oldpath and newpath are not on the  same  mounted  file  system.
          (Linux  permits  a file system to be mounted at multiple points,
          but rename() does not work across different mount  points,  even
          if the same file system is mounted on both.)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top