Tuesday, September 13, 2011

Renaming a file in c

In this post we will find how to rename and move a file in the same drive using c language....
This can be done in c using the rename() function..The prototype of rename is:
int rename(const *char oldname,const *char newname);
On sucess--it returns 0,
On error---it returns -1;
Let us take an example:

#include <stdio.h>
#include<conio.h>
#include<errno.h>
int main(void)
{
   char oldname[80], newname[80];
   int i;
   clrscr();
   printf("Enter File to rename: ");
   gets(oldname);
   printf("\nEnter New name: ");
   gets(newname);
   i=rename(oldname, newname);
     if(i==0)
     {
     printf("rename done");
     }
     else
     {
     if(errno==ENOENT){printf("no such file/directory exists");}
     if(errno==EACCES){printf("access denied");}
     if(errno==ENOTSAM){printf("Drive is not same");}
     }
getch();
   return 0;
}
Let us find the output for different inputs
output:
Enter  File to rename:c:\test.txt
Enter New name:c:\go.txt
rename done
Explanation:it will sucessfully rename the file test to go in the c drive

output:
Enter  File to rename:d:\test.txt
Enter New name:c:\go.txt
Drive is not same
Explanation:Using rename function u can only work within a drive

output:
Enter  File to rename:d:\test.txt
Enter New name:d:\moveinthis\go.txt
rename done
Explanation:You can move the file from one directory to another directory using rename but the condition is that the directories must be in the same drive......

output:
Enter  File to rename:d:\ex.txt
Enter New name:d:\moveinthis\go.txt
no such file/directory exists
Explanation:This message will come if there is no file named as ex.txt present in the d drive......

output:
Enter  File to rename:c:\temp
Enter New name:c:\check
rename done
Explanation:We can rename also a directory  using the rename function,but still the condition is we must work in the same drive.....