Namespaces
Variants
Views
Actions

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

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)
    {
      fprintf(stderr,"fopen() failed in file %s at line # %d\n", __FILE__,__LINE__-3);
      perror("fopen()");
      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)
    {
      fprintf(stderr,"rename() failed in file %s at line # %d\n", __FILE__,__LINE__-3);
      perror("rename()");
      exit(EXIT_FAILURE);
    }
 
    system("ls");
 
    /* Remove file. */
    ret_code = remove(new_file_name);
    if (ret_code != 0)
    {
      fprintf(stderr,"remove() failed in file %s at line # %d\n", __FILE__,__LINE__-3);
      perror("remove()");
      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) [edit]