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.


相关文章
|
2月前
|
存储 缓存 监控
Linux缓存管理:如何安全地清理系统缓存
在Linux系统中,内存管理至关重要。本文详细介绍了如何安全地清理系统缓存,特别是通过使用`/proc/sys/vm/drop_caches`接口。内容包括清理缓存的原因、步骤、注意事项和最佳实践,帮助你在必要时优化系统性能。
213 78
|
23天前
|
缓存 安全 Linux
Linux系统查看操作系统版本信息、CPU信息、模块信息
在Linux系统中,常用命令可帮助用户查看操作系统版本、CPU信息和模块信息
82 23
|
2月前
|
Linux Shell 网络安全
Kali Linux系统Metasploit框架利用 HTA 文件进行渗透测试实验
本指南介绍如何利用 HTA 文件和 Metasploit 框架进行渗透测试。通过创建反向 shell、生成 HTA 文件、设置 HTTP 服务器和发送文件,最终实现对目标系统的控制。适用于教育目的,需合法授权。
82 9
Kali Linux系统Metasploit框架利用 HTA 文件进行渗透测试实验
|
2月前
|
Linux
linux查看目录下的文件夹命令,find查找某个目录,但是不包括这个目录本身?
通过本文的介绍,您应该对如何在 Linux 系统中查看目录下的文件夹以及使用 `find` 命令查找特定目录内容并排除该目录本身有了清晰的理解。掌握这些命令和技巧,可以大大提高日常文件管理和查找操作的效率。 在实际应用中,灵活使用这些命令和参数,可以帮助您快速定位和管理文件和目录,满足各种复杂的文件系统操作需求。
113 8
|
3月前
|
缓存 Java Linux
如何解决 Linux 系统中内存使用量耗尽的问题?
如何解决 Linux 系统中内存使用量耗尽的问题?
251 48
|
2月前
|
存储 监控 Linux
嵌入式Linux系统编程 — 5.3 times、clock函数获取进程时间
在嵌入式Linux系统编程中,`times`和 `clock`函数是获取进程时间的两个重要工具。`times`函数提供了更详细的进程和子进程时间信息,而 `clock`函数则提供了更简单的处理器时间获取方法。根据具体需求选择合适的函数,可以更有效地进行性能分析和资源管理。通过本文的介绍,希望能帮助您更好地理解和使用这两个函数,提高嵌入式系统编程的效率和效果。
115 13
|
3月前
|
Ubuntu Linux 网络安全
linux系统ubuntu中在命令行中打开图形界面的文件夹
在Ubuntu系统中,通过命令行打开图形界面的文件夹是一个高效且实用的操作。无论是使用Nautilus、Dolphin还是Thunar,都可以根据具体桌面环境选择合适的文件管理器。通过上述命令和方法,可以简化日常工作,提高效率。同时,解决权限问题和图形界面问题也能确保操作的顺利进行。掌握这些技巧,可以使Linux操作更加便捷和灵活。
83 3
|
3月前
|
运维 监控 网络协议
运维工程师日常工作中最常用的20个Linux命令,涵盖文件操作、目录管理、权限设置、系统监控等方面
本文介绍了运维工程师日常工作中最常用的20个Linux命令,涵盖文件操作、目录管理、权限设置、系统监控等方面,旨在帮助读者提高工作效率。从基本的文件查看与编辑,到高级的网络配置与安全管理,这些命令是运维工作中的必备工具。
252 3
|
3月前
|
Linux Python
Linux 中某个目录中的文件数如何查看?这篇教程分分钟教会你!
在 Linux 系统中,了解目录下文件数量是常见的需求。本文介绍了四种方法:使用 `ls` 和 `wc` 组合、`find` 命令、`tree` 命令以及编程实现(如 Python)。每种方法都附有详细说明和示例,适合不同水平的用户学习和使用。掌握这些技巧,可以有效提升系统管理和日常使用的效率。
1512 6
|
2月前
|
Ubuntu Linux C++
Win10系统上直接使用linux子系统教程(仅需五步!超简单,快速上手)
本文介绍了如何在Windows 10上安装并使用Linux子系统。首先,通过应用商店安装Windows Terminal和Linux系统(如Ubuntu)。接着,在控制面板中启用“适用于Linux的Windows子系统”并重启电脑。最后,在Windows Terminal中选择安装的Linux系统即可开始使用。文中还提供了注意事项和进一步配置的链接。
52 0