Rename

From aldeid
Jump to navigation Jump to search

Syntax

int rename ( const char * oldname, const char * newname );

Description

Rename file

Changes the name of the file or directory specified by oldname to newname.

This is an operation performed directly on a file; No streams are involved in the operation.

If oldname and newname specify different paths and this is supported by the system, the file is moved to the new location.

If newname names an existing file, the function may either fail or override the existing file, depending on the specific system and library implementation.

Proper file access shall be available.

Parameters

oldname
C string containing the name of an existing file to be renamed and/or moved.
Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
newname
C string containing the new name for the file.
Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).

Return value

If the file is successfully renamed, a zero value is returned.

On failure, a nonzero value is returned.

On most library implementations, the errno variable is also set to a system-specific error code on failure.

Example

Source Run
#include <stdio.h>

int main(int argc, char *argv[])
{
  char oldname[] = "loc1/info.dat";
  char newname[] = "loc2/new.txt";
  int res = 0;

  res = rename(oldname, newname);
  if (res == 0) puts("File successfully renamed");
  else perror("Error renaming file");

  return 0;
}
$ tree
.
├── code
├── code.c
├── loc1
│   └── info.dat
├── loc2
└── makefile

2 directories, 4 files
$ ./code
File successfully renamed
$ tree
.
├── code
├── code.c
├── loc1
├── loc2
│   └── new.txt
└── makefile

2 directories, 4 files