mv'ing files from a C program

Conor P. Cahill cpcahil at virtech.uucp
Fri Nov 16 00:29:52 AEST 1990


In article <22 at mixcom.UUCP> ggvvgg at mixcom.UUCP (Dave Fenske) writes:
>Is there an easy way to do an 'mv' from a C program?

If you are on a BSD based system you have the rename(2) system call.

For other systems without rename you can emulate a move with the
following sequence (assuming that the directories for both files are
on the same filesystem):

		unlink(newfile)
		link(oldfile,newfile)
		unlink(oldfile)

Of course, you should use the appropriate error detection to ensure
that you don't remove the oldfile if the link was not successfull.

If the files are not on the same filesystem, the only way to do it
is a full copy.  You can do this by hand or by calling the mv command.


>I just want to be able to move a recently read file into another directory,
>and wish to avoid having to write it there.  Using the 'system' call is
>not deemed wiable for this application.

You don't have to use system(3), you can use fork/execl(2) (or one of it's 
family of functions) as follows:

	if( fork() == 0 )
		execl("/bin/mv","mv",oldfile,newfile,(char *)0);
	else
		wait((int *)0);

Again, you will probably want to add better error handling, this is just an 
example of one way to do it.	


-- 
Conor P. Cahill            (703)430-9247        Virtual Technologies, Inc.,
uunet!virtech!cpcahil                           46030 Manekin Plaza, Suite 160
                                                Sterling, VA 22170 



More information about the Comp.unix.questions mailing list