linux的目录操作主要有以下几个重要的函数
1.获取绝对路径
#include <unistd.h>
char *get_current_dir_name(void);
函数返回当前的绝对路径
2.改变当前路径
#include <unistd.h>
int chdir(const char *path);
执行完此函数,则通过get_current_dir_name,可以看到绝对路径发生了变化
3.打开某路径
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
返回一个指向目录流的指针
4.读取目录流
#include <sys/types.h>
#include <dirent.h>
struct dirent *readdir(DIR *dir);
The readdir() function returns a pointer to a dirent structure repre-senting the next directory entry in the directory stream pointed to by dir. It returns NULL on reaching the end-of-file or if an error occurred.
读取打开的目录流,返回一个目录信息的结构体
两个重要的结构体
对于这两个结构体,只是有助于理解,无需死记硬背,实在记不起来参数,可以man一下。
DIR结构体的定义如下:
struct __dirstream
{
void *__fd;
char *__data;
int __entry_data;
char *__ptr;
int __entry_ptr;
size_t __allocation;
size_t __size;
__libc_lock_define (, __lock)
};
typedef struct __dirstream DIR;
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 */
char d_name[256]; /* filename */
};
到此,简单的目录所需要的关键的数据结构和关键的函数已经介绍完了。
文件操作的思路
具体的过程和思路应该是
1.首先打开一个路径,那这个路径返回什么呢?一个路径的描述符(类似于文件操作的文件描述符)。
2.现在已经获得了路径的描述符,然后我就可以操作这个路径描述符了(还是类比文件操作的文件描述符)
3.通过读路径描述的操作,获取该目录下的一个个目录描述符结构体指针,然后可以获得每个文件的大小,名字等信息
demo
下面是我自己写的一个简单的demo
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<unistd.h>
int main()
{
printf("%s\n",get_current_dir_name());
chdir("/home/fy");
printf("%s\n",get_current_dir_name());
struct dirent *dirinfo;
DIR *path;
path=opendir(".");
while((dirinfo=readdir(path))!=NULL)
{
printf("%s\n",dirinfo->d_name);
}
closedir(path);
return 0;
}