rename

From cppreference.com
< c‎ | io
Defined in header <stdio.h>
int rename( const char *old_filename, const char *new_filename );

Changes the filename of a file. The file is identified by character string pointed to by old_filename. The new filename is identified by character string pointed to by new_filename.

Contents

[edit] Parameters

old_filename - pointer to a null-terminated string containing the path identifying the file to rename
new_filename - pointer to a null-terminated string containing the new path of the file

[edit] Return value

0 upon success or non-zero value on error.

[edit] Example

rename with error checking. Code renames a file.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char* old_file_name = "C:\\file.txt";
    const char* new_file_name = "C:\\data.txt";
 
    FILE *fp = fopen(old_file_name,"w");
    if (fp == NULL)
    {
      perror("fopen()");
      fprintf(stderr,"fopen() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
      exit(EXIT_FAILURE);
    }
 
    /* Normal processing continues here. */
    fclose(fp);
 
    system("ls");
 
    /* Rename file. */
    int ret_code = rename(old_file_name,new_file_name);
    if (ret_code != 0)
    {
      perror("rename()");
      fprintf(stderr,"rename() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
      exit(EXIT_FAILURE);
    }
 
    system("ls");
 
    /* Remove file. */
    ret_code = remove(new_file_name);
    if (ret_code != 0)
    {
      perror("remove()");
      fprintf(stderr,"remove() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
      exit(EXIT_FAILURE);
    }
 
    return EXIT_SUCCESS;
}

Output:

C:\file.txt
a.out
main.cpp
C:\data.txt
a.out
main.cpp

[edit] See also

erases a file
(function)
C++ documentation for rename