找到当前目录
char *getcwd(char * buf,size_t size)
getcwd函数把当前工作目录的绝对路径名复制到buf中,size指示buf的大小
如果buf不够大,不能装下整个路径名,getcwd返回NULL。
当前目录是指当前页面所在的目录,不是指程序所在的目录,相当于"pwd"命令
//getcwd()
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int arg, char * args[])
{
//获取当前目录
char buf[256]={0};
/*
getcwd()函数头文件是unistd.h
*/
char *res=getcwd(buf,sizeof(buf));
if(res)
{
printf("%s\n",buf);
}
return 0;
}
获取目录列表
--用opendir函数打开目录文件
--用readdir函数读出目录文件内容
--用closedir函数关闭目录文件。
--这些函数都在<dirent.h>头文件中声明
DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
opendir函数打开pathname指向的目录文件,如果错误返回NULL
创建目录--暂时只能手动创建,我还没有好办法
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all file system types */
char d_name[256]; /* filename */
};
//opendir(),readdir(),closedir()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
int main(int arg, char * args[])
{
if(arg<2)
{
printf("请输入一个参数!\n");
return 0;
}
//创建一个目录指针
DIR *dp=NULL;
//定义目录结构指针
struct dirent *drp=NULL;
//打开一个目录
dp=opendir(args[1]);
if(dp==NULL)
{
printf("error msg:%s\n",strerror(errno));
return 0;
}
/*
drp=readdir(dp)这是赋值操作
while判断是drp对象是否为空
readdir(dp)读出目录文件内容,返回值是struct dirent结构体对象指针
*/
while((drp=readdir(dp))!=NULL)
{
//注意:struct dirent在windows和Linux下的定义不同
printf("%s\n",drp->d_name);
}
//关闭目录指针
if(dp!=NULL)
closedir(dp);
return 0;
}