linux目录操作

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值