[comp.os.msdos.programmer] rename

u5533129@ucsvc.ucs.unimelb.edu.au (04/04/91)

Is the rename() function in C guaranteed to fail on an attempt to rename
to an existing file for all C compilers?

The following simple move function works fine compiled under Turbo C, but 
could do horrible things if some other compiler allows renames to existing 
files. 

Please let me know if you know of a C compiler that behaves differently.

Peter

/*
	File move program by Peter Summers.

	Only works between locations on the same device.

	Released to the Public Domain - 3/4/91.
*/

#include <stdio.h>
#include <dir.h>
#include <dos.h>
#include <errno.h>

main(int argc, char *argv[])
  {
  char	spath[128],sdrive[3],sdir[128],sname[9],sext[4];
  char	dpath[128],ddrive[3],ddir[128],dname[9],dext[4];

  struct ffblk	ffblock;

  if (argc<2)
    {
    printf("MOVE <source file name> <destination file name>");
    exit(0);
    }

  /*	Try a simple rename first.	*/

  if(rename(argv[1],argv[2])==0) exit(0);

  /*	If that failed, assume the destination is a directory.	*/

  fnsplit(argv[1],sdrive,sdir,sname,sext);
  fnsplit(argv[2],ddrive,ddir,dname,dext);

  strcat(ddir,dname);
  strcat(ddir,dext);

  if(findfirst(argv[1],&ffblock,FA_ARCH|FA_HIDDEN|FA_RDONLY)==-1)
    {
    perror("MOVE ERROR");
    exit(errno);
    }

  for (;;)
    {
    fnmerge(dpath,ddrive,ddir,ffblock.ff_name,"");
    fnmerge(spath,sdrive,sdir,ffblock.ff_name,"");

    if(rename(spath,dpath)) perror("MOVE ERROR");

    if (findnext(&ffblock)==-1) exit(0);
    }
  }