YouTip LogoYouTip

C Function Rename

# C Library Function - rename() [![Image 3: C Standard Library - ](#) C Standard Library - ](#) rename() is a function in the C standard library used to **rename a file or directory**. rename() is defined in the header file. The C library function **int rename(const char *old_filename, const char *new_filename)** changes the filename pointed to by **old_filename** to **new_filename**. ## Declaration Here is the declaration of the rename() function. int rename(const char *old_filename, const char *new_filename) ### Parameters * **old_filename** -- The original filename (provide the full path if it includes a path). * **new_filename** -- The new filename (can also include a path). ### Return Value * 0 : Success (file/directory renamed successfully). * Non-zero : Failure (common error reasons include insufficient permissions, file not existing, destination already existing, etc.). ### Usage Notes The file must exist, otherwise an error will be returned. If the destination file new_filename already exists, different systems may handle it differently: * On most Unix/Linux systems, rename() will directly overwrite the destination file. * On Windows, if the destination file exists, rename() will fail. Cannot rename across different mount points (partitions/devices). * * * ## Example The following example demonstrates the usage of the rename() function. ## Example #include int main (){ int ret; char oldname[]="file.txt"; char newname[]="newfile.txt"; ret =rename(oldname, newname); if(ret ==0){ printf("File renamed successfully"); }else{ printf("Error: Unable to rename the file"); } return(0); } Suppose we have a text file **file.txt** with the following content. We will use the program above to rename this file. Let's compile and run the above program, which will generate the following message, and the file will be renamed to **newfile.txt**. File renamed successfully [![Image 4: C Standard Library - ](#) C Standard Library - ](#)
← C Function VprintfEvent Key Which β†’