Skip to content

Instantly share code, notes, and snippets.

@TheRealJokerMan
Created October 4, 2021 07:47
Show Gist options
  • Save TheRealJokerMan/0b8320bf25678dbe2fc71f07e1def4fa to your computer and use it in GitHub Desktop.
Save TheRealJokerMan/0b8320bf25678dbe2fc71f07e1def4fa to your computer and use it in GitHub Desktop.
Create a zero-filled binary file.
#! /usr/bin/python3
import argparse
import enum
import pathlib
import sys
class Units(enum.Enum):
Kibibytes = 'KiB'
Mebibytes = 'MiB'
Gibibytes = 'GiB'
Tebibytes = 'TiB'
def __str__(self):
return self.value
def to_bytes(self, number):
UNITS = {
'KiB': 2 ** 10,
'MiB': 2 ** 20,
'GiB': 2 ** 30,
'TiB': 2 ** 40
}
return int(float(number) * UNITS[self.value])
def _parse_arguments():
parser = argparse.ArgumentParser(
prog='bin-file-maker',
description='Create a zero-filled binary file.')
parser.add_argument('path', type=str, help='Path of the file to create.')
parser.add_argument('size', type=float, help='Size of the file to create.')
parser.add_argument('units', type=Units, choices=list(Units),
help='The unit of the size parameter.')
values = None
try:
args = parser.parse_args()
values = vars(args)
values['path'] = pathlib.Path(values['path']).resolve()
values['size'] = values["units"].to_bytes(values["size"])
except SystemExit:
return None
return values
def main():
args = _parse_arguments()
if not args:
return -1
try:
with open(args['path'], 'wb+') as f:
f.seek(args['size'] - 1)
f.write(bytearray(1))
except Exception as ex:
print(ex.message, file=sys.stderr)
return -1
return 0
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment