如何查看文件的大小是否是 4 字节的倍数 [英] How to see if the size of a file is multiple of 4 bytes
问题描述
我正在为大学练习编写 bash 脚本,该脚本读取作为参数传递给它的文件的字节大小并将它们相加.如果大小是 4 字节的倍数,则添加大小.如果不是,我必须把它做成4的倍数.特别是练习的正文是这样写的:如果文件的大小D不是4字节的倍数,则填写最后的Dmod 4 字节,带零."
I'm writing a bash script for a university exercise, which reads the byte size of the files passed to it as arguments and adds them up. The size is added if it is a multiple of 4 bytes. If not, I have to make it a multiple of 4. In particular, the text of the exercise says like this: "If the size D of the file is not a multiple of 4 bytes, fill in the last D mod 4 bytes with zeros. "
现在,为了检查文件的大小是否是 4 字节的倍数,我这样做了,但我不知道这是否正确:
Now, to check if the size of a file is a multiple of 4 bytes I do this, but i don't know if this is right:
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 字节的倍数,则对 4 个字节取零.
Also I would like to know, given the size D of the file (in bytes), how to fill in the last D mod 4 bytes with zeros, if D is not a multiple of 4 bytes.
问题是我不明白填写最后一个D"是什么意思mod 4 字节带零.
The problem is that I don't understand what it means to "fill in the last D mod 4 bytes with zeros ".
推荐答案
不是停在模数处,而是直接计算 null
填充量以与 truncate
一起使用:
Instead of stopping at the modulo, directly compute the null
padding amount to use with 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
这篇关于如何查看文件的大小是否是 4 字节的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!