Last active
August 29, 2015 13:57
-
-
Save udaya1223/9739338 to your computer and use it in GitHub Desktop.
Write unix mv function in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <dirent.h> | |
int main(int ac, char *av[]){ | |
errno = 0; | |
int result = 0; | |
DIR *dir; | |
char buf[512]; | |
if(ac == 3){ | |
dir = opendir(av[2]); | |
if(dir){ | |
char *pch; | |
pch = strrchr(av[1], '/'); | |
if(pch == NULL) sprintf(buf, "%s/%s", av[2], av[1]); | |
else sprintf(buf, "%s/%s", av[2], pch+1); | |
result = rename(av[1], buf); | |
} | |
else{ | |
result = rename(av[1], av[2]); | |
} | |
if(result==-1){ | |
fprintf(stderr, "%s Cannot move from %s to % s\n%s\n", av[0], av[1], av[2], strerror(errno)); | |
exit(EXIT_FAILURE); | |
} | |
}else { | |
fprintf(stderr, "SYNTAX ERROR:\nUsage: %s [Old file name] [New file name]\n", av[0]); | |
exit(EXIT_FAILURE); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment