【问题标题】:How to see if the size of a file is multiple of 4 bytes如何查看文件大小是否为 4 字节的倍数
【发布时间】:2021-04-29 17:16:44
【问题描述】:

我正在为大学练习编写一个 bash 脚本,它读取作为参数传递给它的文件的字节大小并将它们相加。如果它是 4 字节的倍数,则添加大小。如果不是,我必须使它成为 4 的倍数。特别是,练习的文本是这样说的:“如果文件的大小 D 不是 4 字节的倍数,则填写最后一个 D mod 4 个字节,带零。 "

现在,为了检查文件的大小是否是 4 字节的倍数,我这样做了,但我不知道这是否正确:

D=`stat -c '%s' file.txt`  #command sostitution
if (( ($D/4)*4 == $D ))
then 
    echo it's ok
else
    echo it isn't ok
fi

我也想知道,给定文件的大小 D(以字节为单位),如何填写最后一个 D 如果 D 不是 4 字节的倍数,则用 0 对 4 个字节进行模数。

问题是我不明白“填写最后一个D”是什么意思 mod 4 个字节,带零“。

【问题讨论】:

  • 该文件是否可能由objcopy或类似文件生成?

标签: bash sh modulo


【解决方案1】:

尝试以下方法:

d=$(stat -c '%s' file.txt)
if ((d % 4 != 0)); then
   truncate -s "$(( (d + 3) / 4 * 4 ))" file.txt
fi

使用http://shellcheck.net检查您的脚本

【讨论】:

    【解决方案2】:

    直接计算null 填充量以与truncate 一起使用,而不是在模数处停止:

    #!/usr/bin/env sh
    
    # Pad files with null to the alignment
    # align ALIGNMENT FILE...
    # $1: The alignemnt in bytes
    # $@: The filenames to get aligned
    ####
    # Example usage:
    # align 4 file1.txt file2.txt file3.txt
    
    # Take alignment as first argument
    alignment=$1
    
    # Shift first argument out
    shift
    
    # Iterate all remaining arguments as filename
    for filename; do
      # If filename is a real file and has write permission
      if [ -f "$filename" ] && [ -w "$filename" ]; then
        # Get file size in bytes
        size=$(stat -c '%s' "$filename")
    
        # Compute how much padding would be need for alignment
        padding=$((alignment - size % alignment))
    
        # If file need padding
        if [ $padding -gt 0 ]; then
          # Pad file with padding nulls
          truncate -s +$padding "$filename"
        fi
      fi
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多