/* newdir.c create directory and change to it */ #include #include #include #include #include #include #include int main(int argc, char ** argv) { struct stat statbuffer; /*file stat*/ struct dirent * direntry; /* directory entry for readdir */ char * p; DIR * dir; /* stream handle for directory -> opendir */ if (argc != 2) { fprintf(stderr, "Usage: %s newdirectory\n", argv[0]); exit(1); } if (stat(".", &statbuffer) < 0) { perror("stat error with '.'"); exit(2); } if ( (statbuffer.st_mode & S_IFMT) != S_IFDIR) { perror(". no directory?"); exit(3); } /* open directory and scan for argv[1]:*/ dir = opendir("."); while( (direntry = readdir(dir))!=NULL) { if (strcmp(direntry->d_name, argv[1]) == 0) { fprintf(stderr,"%s already exists\n", argv[1]); exit(4); } } /* make newdir: */ if ( (p = (char *) malloc(256)) == NULL) { perror("mcalloc"); exit(5); } if (sprintf(p,"./%s",argv[1]) <= 0) { perror("sprintf"); exit(6); }; if (mkdir(p,0777) < 0) { perror("mkdir"); exit(7); } /* change to this dir */ if ( chdir(p) < 0 ) { perror("chdir"); exit(8); } printf("now working directory: "); fflush(stdout); system("pwd"); exit(0); }