Use bitmasking to keep track of flags

This commit is contained in:
Imbus 2026-02-09 13:36:59 +01:00
parent 117d01fcbe
commit 734c1c10ec

View file

@ -32,6 +32,10 @@
#define BLOCKSIZE (1024 * 1024)
#endif
#define WI_VERIFY (1 << 0)
#define WI_WRITE (1 << 1)
#define WI_ASK (1 << 2)
#define BYTES_TO_MIB(bts) ((double)bts / (1024 * 1024))
#define BAR_WIDTH 50
@ -76,7 +80,7 @@ struct write_job {
size_t bufsize;
size_t block_size;
size_t total_bytes;
char verify_only;
char flags;
} wjob = {0};
typedef struct write_job write_job_t;
@ -114,7 +118,7 @@ int perform_write(write_job_t *job) {
if (read_bytes == 0) {
crc = crc32_finalize(crc);
if (!job->verify_only) {
if (job->flags & WI_WRITE) {
printf("\nWriting done...\n");
assert(job->total_bytes == b_written);
} else
@ -131,7 +135,7 @@ int perform_write(write_job_t *job) {
crc = crc32_update(crc, job->buffer, read_bytes);
if (!job->verify_only) {
if (job->flags & WI_WRITE) {
ssize_t written_bytes = write(block_fd, job->buffer, read_bytes);
if (written_bytes < 0) {
fprintf(stderr, "%s: Write error\n", job->dev_name);
@ -206,14 +210,18 @@ int main(int argc, char *argv[]) {
signal(SIGHUP, int_handler);
signal(SIGTERM, int_handler);
int ask_permission = 1;
wjob.flags = WI_VERIFY | WI_WRITE | WI_ASK;
int c = {0};
while ((c = getopt_long(argc, argv, "vd:hnV", longopts, 0)) != -1) {
switch (c) {
case 'v': ++wjob.verify_only; continue;
case 'v':
wjob.flags |= WI_VERIFY;
wjob.flags &= ~WI_WRITE;
continue;
case 'd': wjob.dev_name = optarg; continue;
case 'h': break;
case 'n': --ask_permission; continue;
case 'n': wjob.flags &= ~WI_ASK; continue;
case 'V': exit(EXIT_SUCCESS);
}
printf("In honor of SwePwnage - the OG disk destroyer\n");
@ -264,13 +272,13 @@ int main(int argc, char *argv[]) {
wjob.total_bytes = file_stat.st_size;
assert(file_stat.st_size >= 0);
if (!wjob.verify_only)
if (wjob.flags & WI_WRITE)
printf("Writing \"%s\" (%.1f MiB) to \"%s\"\n",
basename(wjob.filename),
BYTES_TO_MIB(wjob.total_bytes),
wjob.dev_name);
if (ask_permission && !wjob.verify_only) {
if ((wjob.flags & WI_ASK) && (wjob.flags & WI_WRITE)) {
printf("Is this okay? (y/N): ");
fflush(stdout);
if ('y' != getchar()) {