tags:

views:

351

answers:

3

I was just wondering how could i rename a file on unix platform using a c program without using the standard rename function.any ideas? rename a file in c

+30  A: 

The historical way to rename a file is to use link(2) to create a new hardlink to the same file, then to use unlink(2) to remove the old name.

Martin v. Löwis
+1  A: 

The following is a somewhat ironic solution, that does not use the standard rename(2) system call by itself:

#include <stdlib.h>

if (system("mv file1 file2") != 0)
    perror("system");

It's an indirect usage of rename(2), this syscall is invoked by mv(1).

Andrey Vlasovskikh
Don't forget that 'mv' does considerably more than 'rename()' when the source and target locations are on different file systems.
Jonathan Leffler
+1  A: 

You can use this:

int rename ( const char * oldname, const char * newname );

Example:

#include <stdio.h>
int main()
{
    if ( 0 == rename("old.txt", "new.txt") )
    {
     printf ("Success!\n");
    }

    return 0;
}
fairstar
"Without using the standard rename function"!
Thomas Padron-McCarthy