#include <unistd.h> #include <stdio.h> #include <limits.h> int main(int argc, char* argv[]) { char buf[PATH_MAX]; getcwd(buf, PATH_MAX-1); printf("the current path is :%s\n", buf); return 0; }
设置工作目录:
#include <unistd.h>
int chdir(const char *path);
int fchdir(int fd);
chdir() changes the current working directory of the calling process to the directory specified in path.
fchdir() is identical to chdir(); the only difference is that the directory is given as an open file descriptor.
-----------------------------------
只要对目录有读写权限,就可获取目录信息。
打开目录:opendir
读取目录: readdir
关闭目录:closedir
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
#include <sys/types.h> #include <dirent.h> #include <stdlib.h> #include <stdio.h> int my_readdir(const char* path) { DIR *dirp; struct dirent *ptr; if ( (dirp=opendir(path)) == NULL) { return -1; } while( (ptr=readdir(dirp)) != NULL) { printf("file name is:%s\n", ptr->d_name); } return 0; } int main(int argc, char* argv[]) { if (argc < 2) { exit(0); } if(my_readdir(argv[1]) < 0) { exit(0); } return 0; }