Linux系统调用九、与目录操作相关的系统API

简介: Linux系统调用九、与目录操作相关的系统API

1. getcwd函数

  • 包含头文件
#include <unistd.h>
  • 函数原型
char *getcwd(char *buf, size_t size);
char *getwd(char *buf);
char *get_current_dir_name(void);
  • 函数功能
    These functions return a null-terminated string containing an absolute pathname that is the current working directory of the calling process. 获得进程的当前工作路径。
  • 函数参数
  • buf:缓冲区,用于存放目录。The pathname is returned as the function result and via the argument buf, if present.
  • size:缓冲区大小
  • 函数返回值
  • On success, these functions return a pointer to a string containing the pathname of the current working directory. In the case getcwd() and getwd() this is the same value as buf. 成功返回指向路径名字符串的指针。
  • On failure, these functions return NULL, and errno is set to indicate the error. The contents of the array pointed to by buf are undefined on error. 失败返回NULL。

2. chdir函数

  • 包含头文件
#include <unistd.h>
  • 函数原型
int chdir(const char *path);
int fchdir(int fd);
  • 函数功能
    chdir() changes the current working directory of the calling process to the directory specified in path.改变进程的工作路径。
  • 函数参数
  • path:目标路径,也就是将当前进程的工作路径改为path。
  • 函数返回值
  • 成功返回0。On success, zero is returned.
  • 失败返回-1且设置errno。On error, -1 is returned, and errno is set appropriately.

示例:改变进程当前工作路径并打屏

/************************************************************
  >File Name  : chdir_test.c
  >Author     : QQ
  >Company    : QQ
  >Create Time: 2022年05月16日 星期一 21时36分37秒
************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char*argv[])
{
  /*切换当前进程的工作路径,注意是当前进程,也就是main进程的工作路径*/
  chdir(argv[1]);
  /*在新的路径创建一个文件来证明路径切换成功*/
  int fd = open("hello.txt", O_CREAT | O_RDONLY);
  close(fd);
  char buf[512];
  getcwd(buf, sizeof(buf));
  printf("current path : %s\n", buf);
  return 0;
}

首先,看测试结果中打印的内容,getcwd()函数获取到的路径确实是我们通过chdir()函数指定的路径,并且test路径从无到有增加了一个文件,也证明我们切换工作路径成功了。但是有些人可能会有一个疑惑,看途中的红色箭头标记,既然当前工作路径已经切换为①所标识的路径了,那么为什么②处显示的工作路径还是原来的路径呢?这是因为,我们在程序中使用chdir()函数切换的路径是进程 ./chdir_test 的路径,也就是说 ./chdir_test 的路径被切换为①了,并且测试结果(hello.txt文件的创建)也证明切换成功。而②所标识的路径是当前shell进程的工作路径,它们俩根本不是一回事。

3. mkdir函数

  • 包含头文件
#include <sys/stat.h>
#include <sys/types.h>
  • 函数原型
int mkdir(const char *pathname, mode_t mode);
  • 函数功能
    mkdir() attempts to create a directory named pathname. 创建一个目录。
  • 函数参数
  • pathname:路径名
  • mode:(mode & ~umask & 0777),和文件不同的是,目录必须有可执行权限才能进入目录,所以新建的目录必须要有可执行权限。(如果目录没有可执行权限,那么将无法进入该目录,所以新建时可以给满权限777)
  • 函数返回值
    mkdir() returns zero on success, or -1 if an error occurred (in which case, errno is set appropriately).

示例:使用mkdir命令和mkdir()函数分别新建一个目录

/************************************************************
  >File Name  : mkdir_test.c
  >Author     : QQ
  >Company    : QQ
  >Create Time: 2022年05月16日 星期一 22时11分29秒
************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char* argv[])
{
  if(argc < 2)
  {
    printf("not found filename\n");
    return -1;  
  }
  mkdir(argv[1], 0777);
  return 0;
}

通过这个例子可以得到,如果想要使用mkdir()函数创建的目录达到和mkdir命令创建目录有一样的权限,可以给mode参数0777满权限。

4. rmdir函数

  • 包含头文件
#include <unistd.h>
  • 函数原型
int rmdir(const char *pathname);
  • 函数功能
    rmdir() deletes a directory, which must be empty. 只能删除空目录。
  • 函数参数
  • pathname:文件名及路径
  • 函数返回值
  • 成功返回0。On success, zero is returned.
  • 失败返回-1且设置errno。On error, -1 is returned, and errno is set appropriately.

5.opendir函数

  • 包含头文件
#include <sys/types.h>
#include <dirent.h>
  • 函数原型
DIR *opendir(const char *name);
DIR *fdopendir(int fd);
  • 函数功能
    The opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the directory stream. The stream is positioned at the first entry in the directory. 打开目录。
  • 函数参数
  • name:目录名字。
  • 函数返回值
  • The opendir() and fdopendir() functions return a pointer to the directory stream. 返回一个指向目录流的指针DIR*,指向目录项的信息。
  • On error, NULL is returned, and errno is set appropriately.

6. readdir函数

  • 包含头文件
#include <dirent.h>
  • 函数原型
struct dirent *readdir(DIR *dirp);
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);
  • 函数功能
    读目录。
  • 函数参数
  • dirp:传入opendir返回的指针。
  • 函数返回值
  • On success, readdir() returns a pointer to a dirent structure. If the end of the directory stream is reached, NULL is returned and errno is not changed. 成功返回一个结构体,结构体定义如下
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 */
           };
  • 判断读到内容的类型,依据是结构体成员d_type,类型如下
/*
d_type:
       DT_BLK      This is a block device. 块设备
       DT_CHR      This is a character device. 字符设备
       DT_DIR      This is a directory. 目录
       DT_FIFO     This is a named pipe (FIFO). 管道
       DT_LNK      This is a symbolic link. 符号链接(软链接)
       DT_REG      This is a regular file. 普通文件
       DT_SOCK     This is a Unix domain socket. socket
       DT_UNKNOWN  The file type is unknown. 未知
*/
  • On error, NULL is returned and errno is set appropriately.

7. closedir函数

  • 包含头文件
#include <sys/types.h>
#include <dirent.h>
  • 函数原型
int closedir(DIR *dirp);
  • 函数功能
    关闭目录。
  • 函数参数
  • dirp:传入opendir返回的指针。
  • 函数返回值
  • The closedir() function returns 0 on success.
  • On error, -1 is returned, and errno is set appropriately.

示例:递归子目录统计普通文件个数

/************************************************************
  >File Name  : count_file.c
  >Author     : QQ
  >Company    : QQ
  >Create Time: 2022年05月17日 星期二 12时40分35秒
************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
int gFileNum = 0;
void file_count(char* dirname)
{
  /*打开目录*/
  DIR* dir = opendir(dirname);
  if(dir == NULL) /*打开失败则退出*/
  {
    perror("opendir err");
    exit(-1); 
  } 
  struct dirent* dentp = NULL;
  while((dentp = readdir(dir)) != NULL) /*不为NULL说明未读到末尾*/
  {
    if(dentp->d_type == DT_DIR) /*如果是目录则递归进入目录*/
    {
      if((strcmp(".", dentp->d_name) == 0) || (strcmp("..", dentp->d_name) == 0)) /*如果是当前目录或上一级目录则跳过*/
      {
        continue; 
      }
      /*每次递归都要把上一级目录加上,不然的话,进程找不到子目录所在的路径*/
      char namebuf[512];
      memset(namebuf, 0, sizeof(namebuf));
      sprintf(namebuf, "%s/%s", dirname, dentp->d_name);
      file_count(namebuf);
    }
    if(dentp->d_type == DT_REG) /*如果是文件,则计数*/
    {
      gFileNum++;
    }
  }
  closedir(dir);
}
int main(int argc, char* argv[])
{
  if(argc != 2)
  {
    printf("tip: ./exe dirname\n");
    return -1;  
  }
  /*递归目录,统计普通文件个数*/
  file_count(argv[1]);
  printf("num: %d\n", gFileNum);
  return 0;
}

编译运行,并通过shell命令find来验证结果

shell命令统计文件个数的命令

find ./ -type f | wc -l

8. 目录读写位置函数

8.1 rewinddir()把目录指针恢复到起始位置

  • 包含头文件
#include <sys/types.h>
#include <dirent.h>    
  • 函数原型
void rewinddir(DIR *dirp);

8.2 telldir()获取目录读写位置

  • 包含头文件
#include <dirent.h>
  • 函数原型
long telldir(DIR *dirp);

8.3 seekdir()修改目录读写位置

  • 包含头文件
#include <dirent.h>
  • 函数原型
void seekdir(DIR *dirp, long offset);
  • 函数返回值
    On success, the telldir() function returns the current location in the directory stream. On error, -1 is returned, and errno is set appropriately.


相关文章
|
存储 Linux
Linux 目录名称
Linux系统目录结构简介:根目录(/)下包含各类功能目录,如/bin存放用户命令,/etc存储配置文件,/home为用户主目录,/var记录日志等可变数据,/usr存放用户工具,/tmp用于临时文件。各目录分工明确,保障系统有序运行。(238字)
495 5
|
数据采集 机器学习/深度学习 搜索推荐
利用通义大模型构建个性化推荐系统——从数据预处理到实时API部署
本文详细介绍了基于通义大模型构建个性化推荐系统的全流程,涵盖数据预处理、模型微调、实时部署及效果优化。通过采用Qwen-72B结合LoRA技术,实现电商场景下CTR提升58%,GMV增长12.7%。文章分析了特征工程、多任务学习和性能调优的关键步骤,并探讨内存优化与蒸馏实践。最后总结了大模型在推荐系统中的适用场景与局限性,提出未来向MoE架构和因果推断方向演进的建议。
2087 11
|
JSON 搜索推荐 算法
利用API提升电商用户体验:个性化推荐系统
在电商竞争激烈的当下,个性化推荐系统成为提升用户粘性与转化率的关键。本文详解如何通过API集成高效接入先进推荐算法,实现实时精准推荐,优化用户体验,提升业务增长。
|
存储 人工智能 Java
Spring AI与DeepSeek实战四:系统API调用
在AI应用开发中,工具调用是增强大模型能力的核心技术,通过让模型与外部API或工具交互,可实现实时信息检索(如天气查询、新闻获取)、系统操作(如创建任务、发送邮件)等功能;本文结合Spring AI与大模型,演示如何通过Tool Calling实现系统API调用,同时处理多轮对话中的会话记忆。
3240 57
|
算法 API 数据库
生鲜电商技术实践:基于保质期API的自动下架系统保障食品安全
基于保质期提醒API与自动化工作流,实现生鲜商品临期智能预警与自动下架。通过设定差异化预警阈值(如蔬菜2天、冷冻品7天),每日扫描数据库并触发下架指令,确保食品安全合规,降低损耗与客诉,提升运营效率。
|
机器学习/深度学习 人工智能 供应链
淘宝API智能补货系统:库存周转率提升50%的奥秘
在电商竞争激烈的当下,库存管理效率决定企业成败。淘宝API智能补货系统融合人工智能与淘宝开放接口,实现库存自动化管理,大幅提升库存周转率,降低运营成本,助力企业实现高效、智能、精益的供应链管理。
|
Linux 定位技术
Linux系统中的cd命令:目录切换技巧
踏过千山,越过万水,人生就是一场不断前行的旅程,总充满了未知与挑战。然而,“cd”命令如同你的旅伴,会带你穿梭在如棋盘一般的文件系统中,探索每一处未知。希望你能从“cd”命令中找到乐趣,像是掌控了一种络新妙的魔法,去向未知进发,开始你的探索之旅。
652 24
|
监控 安全 API
京东 API 接口:打造高效京东店铺订单处理系统
在电商竞争激烈的环境下,京东店铺需提升订单处理效率以优化用户体验与收益。本文介绍如何利用京东开放平台的API接口,构建高效订单处理系统,涵盖订单查询、库存同步、物流跟踪等功能,助力商家实现自动化管理,显著提升运营效率与客户满意度。
|
机器学习/深度学习 JSON 监控
拼多多API库存预警系统:避免缺货损失千万!
在电商运营中,缺货可能导致订单流失与经济损失,拼多多推出的API库存预警系统可实时监控库存,及时预警,降低缺货风险。系统支持多语言集成,商家可快速构建自动化监控与补货流程,提升供应链效率,保障销售连续性。
1089 0