Using rename() C function to change a filename


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro with SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Using rename() C function to change a filename in C program

To show: How to use the rename() C function to rename a file with new name




// Using rename() function to change a filename

#include <stdio.h>


void main(void)


char oldname[80], newname[80];


printf("Enter current filename: ");

gets_s(oldname, 80);

printf("Enter new name for file: ");

gets_s(newname, 80);

if(rename(oldname, newname) == 0)


printf("%s has been rename %s.\n", oldname, newname);




fprintf(stderr, "An error has occurred renaming %s.\n", oldname);




Output example:


Enter current filename: C:\testsix.txt

Enter new name for file: C:\newsix.txt

C:\testsix.txt has been rename C:\newsix.txt.

Press any key to continue . . .



C and C++ Programming Resources | C & C++ Code Example Index