1、获取当前工作目录
C程序中调用getcwd函数可以获取当前的工作目录
char *getcwd(char * buf,size_t size);
参数:
buf:输出参数,获取到的目录写入buf中
size:buf的长度
返回值:
成功:返回buf
失败,BULL,如果目录名超过参数size长度,返回NULL
使用实例:
char strpwd[301];
memset(strpwd,0,sizeof(strpwd));
getcwd(strpwd,300);
printf("当前目录是:%s\n",strpwd);
2、切换工作目录
就像我们在shell中使用cd命令切换目录一样,在C程序中使用chdir函数来改变工作目录
int chdir(const char *path);
参数:
path:切换的目录
返回值:0-切换成功;非0-失败。
3、目录创建删除
和mkdir,rm用法一样
int mkdir(const char *pathname, mode_t mode);
int rmdir(const char *pathname);
4、获取目录中的文件列表
1、包含头文件
#include <dirent.h>
2、打开目录的函数opendir
DIR *opendir(const char *pathname);
3、读取目录的函数readdir
目录结构体:
d_name文件名或目录名。
d_type描述了文件的类型,有多种取值,最重要的是8和4,8-常规文件(A regular file);4-目录(A directory)
struct dirent
{
long d_ino; // inode number 索引节点号
off_t d_off; // offset to this dirent 在目录文件中的偏移
unsigned short d_reclen; // length of this d_name 文件名长
unsigned char d_type; // the type of d_name 文件类型
char d_name [NAME_MAX+1]; // file name文件名,最长255字符
};
struct dirent *readdir(DIR *dirp);
4、关闭目录的函数closedir
int closedir(DIR *dirp);
5、使用示例程序
#include <stdio.h>
#include <dirent.h>
int main(int argc,char *argv[])
{
if (argc != 2) { printf("请指定目录名。\n"); return -1; }
DIR *dir; // 定义目录指针
// 打开目录
if ( (dir=opendir(argv[1])) == 0 ) return -1;
// 用于存放从目录中读取到的文件和目录信息
struct dirent *stdinfo;
while (1)
{
// 读取一条记录并显示到屏幕
if ((stdinfo=readdir(dir)) == 0) break;
printf("name=%s,type=%d\n",stdinfo->d_name,stdinfo->d_type);
}
closedir(dir); // 关闭目录指针
}