Skip to content

Instantly share code, notes, and snippets.

@udaya1223
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save udaya1223/9739338 to your computer and use it in GitHub Desktop.
Save udaya1223/9739338 to your computer and use it in GitHub Desktop.
Write unix mv function in C
#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