linux目录操作

来源:互联网 发布:淘宝美工是干什么的 编辑:程序博客网 时间:2024/05/17 01:05

获取当前路径

#include <unistd.h>

char *getcwd(char *buf, size_t size);
char *getwd(char *buf);

char *get_current_dir_name(void);

这些函数都返回程序到当前工作路径

get_current_dir_name() 将通过malloc申请一段足够大的空间来存放当前路径。

getwd() 则不申请任何空间,参数buf被指定为MAX_PATH长度。

MAX_PATH是C语言运行时中通过#define指令定义的一个宏常量,它定义了编译器所支持的最长全路径名的长度。

如果当前工作路径长度大于MAX_PATH则返回NULL,否则返回当前路径字符串。


切换路径

#include <unistd.h>
int chdir(const char *path);

创建文件

#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
返回0表示成功,返回-1表述出错。使用该函数需要包含头文件sys/stat.h
mode 表示新目录的权限


目录扫描

int scandir(const char* dirname,//目录名
                struct dirent*** namelist,//返回目录列表
                int (*)(struct dirent*),//回调函数,过滤目录
                                                    //NULL:不过滤
                int (*)(struct dirent*,struct dirent*)//排序返回目录
                                                                        //NULL:不排序
                );

#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <dirent.h>main(){int i;int r;int newfd;char path[200];struct dirent **list;//获取当前路径getcwd(path, 200);printf("%s\n", path);getwd(path);printf("%s\n", path);printf("%s\n", get_current_dir_name());//切换路径chdir("/home");printf("%s\n", get_current_dir_name());//创建文件mkdir("dir", 0);//扫描目录printf("=========\n");r=scandir(path, &list, 0, 0); //返回目录个数for(i=0; i<r; i++)printf("%s\n", list[i]->d_name);}



0 0