Linux下批量创建文件夹

检测文件是否存在

这里的文件包含普通文件或者是目录文件,下面是CentOS 7环境下的测试.

cpp 复制代码
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>

int main()
{
  int ret = access("../lesson01/file.txt", F_OK);
  if (ret == 0)
  {
    std::cout << "存在" << std::endl;
  }
  else
  {
    std::cout << "不存在" << std::endl;
  }
  return 0;
}
shell 复制代码
[qkj@Qkj lesson01]$ ll
total 4
-rw-rw-r-- 1 qkj qkj 261 Aug 30 10:18 test.cc
[qkj@Qkj lesson01]$ 
[qkj@Qkj lesson01]$ g++ test.cc 
[qkj@Qkj lesson01]$ ./a.out 
不存在
[qkj@Qkj lesson01]$ 

说一下access函数,这是一个检测文件是否存在的函数,我们这里只是简绍,详细的函数明细看man手册

  • pathname: 文件名(注意带上路径,可以是绝对路径,也可以是相对的)
  • mode : 直接设为F_OK,仅仅是为了检测文件是否存在
cpp 复制代码
NAME
       access - check real user's permissions for a file

SYNOPSIS
       #include <unistd.h>

       int access(const char *pathname, int mode);

创建目录

这里也说一下我们在CentOS 7环境下下如何创建目录.

cpp 复制代码
NAME
       mkdir - make a directory

SYNOPSIS
       #include <sys/stat.h>

       int mkdir(const char *path, mode_t mode);

参数解释

  • path: 目录名,带路径
  • mode:目录的权限,可以使用八进制

下面是代码演示

cpp 复制代码
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <string>

int main()
{
  umask(2);
  std::string str = "../lesson";
  for (int i = 1; i < 27; i++)
  {
    std::string s = str;
    if (i < 10)
      s += '0';
    s += std::to_string(i);
    int ret = access(s.c_str(), F_OK);
    if (ret == 0)
    {
      std::cout << s << " 存在" << std::endl;
    }
    else
    {
      mkdir(s.c_str(), 0777);
    }
  }

  return 0;
}
相关推荐
春日见1 小时前
如何入门端到端自动驾驶?
linux·人工智能·算法·机器学习·自动驾驶
dys_Codemonkey1 小时前
如何在树莓派上用 VS Code 优雅直连内部的 Ubuntu 子系统/容器用来访问容器内的文件和代码?
linux·运维·ubuntu·树莓派
炸膛坦客2 小时前
Linux - Ubuntu - PC端:(五)shell 操作(终端命令,2026)→ 3)基础命令,27 个常用命令
linux·ubuntu
·醉挽清风·2 小时前
学习笔记—Linux—文件IO
linux·服务器·学习
宁波阿成2 小时前
OpenClaw 在 Ubuntu 22.04.5 LTS 上的安装与问题处理记录
java·linux·ubuntu·openclaw·龙虾
徐子元竟然被占了!!3 小时前
Linux的cat
linux·运维·服务器
坐吃山猪4 小时前
Python进度条
linux·服务器·python
IMPYLH5 小时前
Linux 的 b2sum 命令
linux·运维·服务器·bash
celeste03105 小时前
Redis Summary
linux·运维·服务器·redis·笔记
Sylvan.C5 小时前
Windows+Ubuntu 双系统安装超详细保姆级教程2026,包括系统安装、英伟达独显驱动安装以及双系统时间同步的所有过程
linux·运维·ubuntu