文件IO下目录操作
1、打开目录opendir()
#include <sys/types.h>
include <dirent.h>
DIR *opendir(const char *name);
返回值:成功返回目录流指针,失败返回NULL;
参数:name:目录名
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
DIR *dir = opendir(".");//打开当前目录
if(dir == NULL)
{
perror("opendir");
return -1;
}
printf("success!\n");
return 0;
}
2、读取目录 redadir()
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
返回值:成功返回对应目录项结构体指针,失败返回NULL;
3.关闭目录
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
struct dirent *fl;
DIR *dir = opendir(".");
if(dir == NULL)
{
perror("opendir");
return -1;
}
while((fl = readdir(dir)) != NULL)
{
if(fl->d_name[0] != '.')
{
printf("%s ", fl->d_name);
}
}
printf("\n");
closedir(dir);
return 0;
}
4.获取文件属性
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
int lstat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf);
返回值:成功返回0,失败返回-1;
参数:
path:文件名(包含路径)
S_IFMT 0170000 文件类型掩码
st_mode & S_IFMT == S_IFREG --> 普通文件
**== S_IFDIR --> 目录文件**
S_IFSOCK 0140000 socket
S_IFLNK 0120000 symbolic link
S_IFREG 0100000 regular file
S_IFBLK 0060000 block device
S_IFDIR 0040000 directory
S_IFCHR 0020000 character device
S_IFIFO 0010000 FIFO
st_mode & 对应权限宏 == 宏本身 则拥有对应权限
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
S_IRGRP 00040 group has read permissio
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
struct dirent *fl;
struct stat buf;
int ret = 0;
DIR *dir = opendir(".");
if(dir == NULL)
{
perror("opendir");
return -1;
}
while((fl = readdir(dir)) != NULL) //读取目录项
{
if(fl->d_name[0] != '.')
{
ret = lstat(fl->d_name, &buf); //获取文件属性
if(ret < 0)
{
perror("lstat");
return -1;
}
localtime(&buf.st_ctime);
switch(buf.st_mode & S_IFMT)
{
case S_IFREG:
printf("-"); break;
case S_IFDIR:
printf("d"); break;
}
printf(" %d %d %s\n",buf.st_nlink ,buf.st_size, fl->d_name);
}
}
printf("\n");
closedir(dir);
return 0;
}