Moving Files

The mv(1) command uses the link(2) and unlink(2) calls in order to move a file. However, if the file is moved to another file system, the mv(1) command must copy it. Assuming that the file is being moved within the same file system, an example command looks like this:

$ mv ./a.out ./bin/my_app
					

In C terms, this is accomplished as follows:

if ( link("./a.out","./bin/my_app") == -1 ) {
    fprintf(stderr,"%s: link(2)
",strerror(errno));
    abort();
}
if ( unlink("./a.out") == -1 ) {
    fprintf(stderr,"%s: unlink(2)
",strerror(errno));
    abort();
}

The idea behind moving a file is to create a new link and then remove the old link. This gives the illusion of moving the file from one path to another. However, if the source and destination pathnames are on different file systems, you will get the error EXDEV.

Note

EXDEV—Cross-device link. When link(2) returns this error, it indicates that the operation failed because both pathnames were not on the same file system.


While pathnames can be moved using individual calls to link(2) and unlink(2), the operation occurs frequently enough that the rename(2) function has been provided for convenience. This simplifies your coding effort, since you have to test only one source of error instead of two. The synopsis for this function is as follows:

#include <stdio.h>

int rename(const char *from, const char *to);

The rename(2) function returns 0 if it succeeds. Otherwise the value -1 is returned and an error code is provided in errno.

It is also worth noting that if the final component of the pathname from is a symbolic link, the symbolic link is renamed—not the file or directory that the symbolic link points to.

Warning

The rename(2) function will unlink(2) the to pathname if it already exists.

Additionally, SGI IRIX 6.5 documents this function as being capable of returning EINTR if a signal is caught.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.79.88