How to rename a directory in C?

Viewed 1558

I searched online to find that how to change the directory name? But I found nothing. All I found was rename() that was changing filenames. I want to change a directory name. Linux uses mv command for renaming a directory but if the directory contains large files then moving will take time more right? I want to do this in C.

2 Answers

On every file system I can think of, renaming a directory doesn't actually involve moving the files to a new location but rather changing a record in the file system.

To move a directory on Windows:

if(!MoveFileW(L"C:\\Path\\OldDirName", L"C:\\Path\\NewDirName"))
{
     // Operation failed
}

On *nix:

if(rename("/path/olddirname", "/path/newdirname") != 0)
{
    // Operation failed
}

Wrapper macros:

#ifdef __linux__
#define MvDir(old, new) (rename((old), (new)) != 0)
#elif defined(WINVER)
#define MvDir(old, new) !(MoveFileW((L ## old), (L ## new))
#endif

This also automatically wraps the success-test of the expression into a 1/0 value for you.

...how to change the directory name? ...All I found was rename() that was changing filenames.

No, that's incorrect. rename is totally fine for renaming directories, also.

Linux uses mv command for renaming a directory but if the directory contains large files then moving will take time more right?

The mv command is typically implemented using rename, which is very fast. Renaming a directory does not necessarily require moving (or doing anything with) the files in it.

If you're doing a more complicated rename, like trying to rename a/b/c to d/e/f, and if this ends up trying to move things onto a different mounted filesystem, then a simple directory rename won't work, and yes, actually "moving" (actually copying) of files would be required. In that case, the rename() call will fail, so you'll know. (errno should contain EXDEV.)

In the cross-device case, the mv command will do the expensive work of copying files, but only if it has to.

If you use rename from a C program, you'll get a quick rename for renames on the same filesystem, and an error for renames that attempt to cross filesystems, and you'll never get any expensive copies unless you code them up yourself.

Related