rename() — Rename File

Format

#include <stdio.h>
int rename(const char *oldname, const char *newname);

Language Level: ANSI

Threadsafe: Yes.

Description

The rename() function renames the file specified by oldname to the name given by newname. The oldname pointer must specify the name of an existing file. The newname pointer must not specify the name of an existing file. You cannot rename a file with the name of an existing file. You also cannot rename an open file.

The file formats that can be used to satisfy the new name depend on the format of the old name. The following table shows the valid file formats that can be used to specify the old file name and the corresponding valid file formats for the new name.

If the format for both new name and old name is lib/file(member), then the file cannot change. If the file name changes, rename will not work. For example, the following is not valid: lib/file1(member1) lib/file2(member1).

Old Name New Name
lib/file(member) lib/file(member), lib/file, file, file(member)
lib/file lib/file, file
file lib/file, file
file(member) lib/file(member), lib/file, file, file(member)

Return Value

The rename() function returns 0 if successful. On an error, it returns a nonzero value.

The value of errno may be set to ECONVERT (conversion error).

Example that uses rename()

This example takes two file names as input and uses rename() to change the file name from the first name to the second name.

#include <stdio.h>
 
int main(int argc, char ** argv )
{
  if ( argc != 3 )
    printf( "Usage: %s old_fn new_fn\n", argv[0] );
  else if ( rename( argv[1], argv[2] ) != 0 )
    perror ( "Could not rename file" );
}

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]