Skip to content

Instantly share code, notes, and snippets.

@udaya1223
Last active Aug 29, 2015
Embed
What would you like to do?
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