Linux C 目录操作

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描述了文件的类型,有多种取值,最重要的是848-常规文件(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);   // 关闭目录指针
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

讳疾忌医丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值