字母计数法 Unix split 命令源码阅读与分析

「字母序列」计数法,其实类似于26进制计数系统,只是使用字母代替数字

在这种系统中,每个位置可以取从az的任何字母,其中a代表0,b代表1,以此类推,直到z代表25。当一个位置上的字母超过z时,就像在十进制中一样进位,但是是从aa开始而不是从10开始。

这种计数法经常用于生成有序的字符串序列,例如:

  • 最常见的是Excel的列标题
  • split命令生成的文件后缀,参考前文
  • 以及Jvet会议序号。

前文编写了字母计数法和阿拉伯数字的转换脚本,对ascii码直接强硬转换,比较僵硬(只适用于26-676范围内的split生成文件) 而且扩展性较差。这次遂来分析一下Linux系统中的split命令是通过怎么样的算法实现的。

split 是 coreutils 的一部分,也是GNU操作系统中的基本文件。源代码库可以在这里看到。可以看到,在 split 命令的源代码中,生成字母顺序递增的后缀(例如 "aa", "ab", "ac" 等)的逻辑是由next_file_name 函数实现的。

c 复制代码
static void
next_file_name (void)
{
  /* Index in suffix_alphabet of each character in the suffix.  */
  static idx_t *sufindex;
  static idx_t outbase_length;
  static idx_t outfile_length;
  static idx_t addsuf_length;
​
​
  if (! outfile)
    {
      bool overflow, widen;
​
​
new_name:
      widen = !! outfile_length;
​
​
      if (! widen)
        {
          /* Allocate and initialize the first file name.  */
​
​
          outbase_length = strlen (outbase);
          addsuf_length = additional_suffix ? strlen (additional_suffix) : 0;
          overflow = ckd_add (&outfile_length, outbase_length + addsuf_length,
                              suffix_length);
        }
      else
        {
          /* Reallocate and initialize a new wider file name.
             We do this by subsuming the unchanging part of
             the generated suffix into the prefix (base), and
             reinitializing the now one longer suffix.  */
​
​
          overflow = ckd_add (&outfile_length, outfile_length, 2);
          suffix_length++;
        }
​
​
      idx_t outfile_size;
      overflow |= ckd_add (&outfile_size, outfile_length, 1);
      if (overflow)
        xalloc_die ();
      outfile = xirealloc (outfile, outfile_size);
​
​
      if (! widen)
        memcpy (outfile, outbase, outbase_length);
      else
        {
          /* Append the last alphabet character to the file name prefix.  */
          outfile[outbase_length] = suffix_alphabet[sufindex[0]];
          outbase_length++;
        }
​
​
      outfile_mid = outfile + outbase_length;
      memset (outfile_mid, suffix_alphabet[0], suffix_length);
      if (additional_suffix)
        memcpy (outfile_mid + suffix_length, additional_suffix, addsuf_length);
      outfile[outfile_length] = 0;
​
​
      free (sufindex);
      sufindex = xicalloc (suffix_length, sizeof *sufindex);
​
​
      if (numeric_suffix_start)
        {
          affirm (! widen);
​
​
          /* Update the output file name.  */
          idx_t i = strlen (numeric_suffix_start);
          memcpy (outfile_mid + suffix_length - i, numeric_suffix_start, i);
​
​
          /* Update the suffix index.  */
          idx_t *sufindex_end = sufindex + suffix_length;
          while (i-- != 0)
            *--sufindex_end = numeric_suffix_start[i] - '0';
        }
​
​
#if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
      /* POSIX requires that if the output file name is too long for
         its directory, 'split' must fail without creating any files.
         This must be checked for explicitly on operating systems that
         silently truncate file names.  */
      {
        char *dir = dir_name (outfile);
        long name_max = pathconf (dir, _PC_NAME_MAX);
        if (0 <= name_max && name_max < base_len (last_component (outfile)))
          error (EXIT_FAILURE, ENAMETOOLONG, "%s", quotef (outfile));
        free (dir);
      }
#endif
    }
  else
    {
      /* Increment the suffix in place, if possible.  */
​
​
      idx_t i = suffix_length;
      while (i-- != 0)
        {
          sufindex[i]++;
          if (suffix_auto && i == 0 && ! suffix_alphabet[sufindex[0] + 1])
            goto new_name;
          outfile_mid[i] = suffix_alphabet[sufindex[i]];
          if (outfile_mid[i])
            return;
          sufindex[i] = 0;
          outfile_mid[i] = suffix_alphabet[sufindex[i]];
        }
      error (EXIT_FAILURE, 0, _("output file suffixes exhausted"));
    }
}

可以看到,有几个关键的变量:

  1. sufindex:指针数组,存储当前后缀中每个字符在字母表suffix_alphabet中的索引。
  2. outbase_length:输出文件基本名(不包括后缀)的长度。
  3. outfile_length:输出文件名的总长度(包括基本名和后缀)。
  4. addsuf_length:额外的后缀的长度。
  5. outfile:字符指针,指向当前正在构建的输出文件名。
  6. outfile_midoutfile中指向后缀开始位置的指针。

代码逻辑分为两部分:

  • 初始化新文件名:

    • 如果是第一次调用,分配并初始化文件名。
    • 如果需要扩展后缀(即已经用完了所有可能的后缀组合),则重新分配更长的文件名,并将生成的后缀的不变部分合并到前缀中,然后重新初始化一个更长的后缀。
  • 增加现有后缀:

    • 在现有后缀上递增,如果可能的话,直接在原地完成。
    • 如果当前字符已经是suffix_alphabet中的最后一个字符,那么将该位置重置为suffix_alphabet的第一个字符,并向前进位。
    • 如果所有的后缀字符都已经用完,那么会报错,提示输出文件后缀已耗尽。

具体来说,整个函数的工作流程是首先检查是否需要创建一个新的文件名(如果outfile为空),然后尝试在现有的后缀上递增;如果递增失败(因为已经达到最大可能的后缀),则扩展后缀长度并重新开始。

嗯,,比想象中多坑,,

相关推荐
聚客AI12 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v15 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
CYRUS_STUDIO15 小时前
用 Frida 控制 Android 线程:kill 命令、挂起与恢复全解析
android·linux·逆向
熊猫李17 小时前
rootfs-根文件系统详解
linux
惯导马工17 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农18 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了19 小时前
AcWing学习——双指针算法
c++·算法
dessler19 小时前
Hadoop HDFS-高可用集群部署
linux·运维·hdfs
moonlifesudo19 小时前
322:零钱兑换(三种方法)
算法
泽泽爱旅行19 小时前
awk 语法解析-前端学习
linux·前端