A C Program a Day

2019-10-02 - dd progress display

I often run dd to copy a disk image onto a USB key. But by default, dd doesn't show its progress as it runs, and it can sometimes take a while. So here's a small program which is like cat, but it prints how much data it has outputted to stderr. You can use it with dd like this:

dd if=something.iso | ./2019_10_02 | dd of=/dev/sdb
Today's procedure is writed, which outputs a floating-point number.

Downloads



#include "procs-2019-10-02.c"

int main(void) {
	static char buffer[1L<<20];
	long total = 0;
	ssize_t bytesread;
	while ((bytesread = read(STDIN, buffer, sizeof buffer)) > 0) {
		total += (long)bytesread;
		write(STDERR, "\r", 1);
		if (total >= (1L<<30)) {
			writed(STDERR, (double)total / (double)(1L<<30), 1);
			write(STDERR, "GB", 2);
		} else if (total >= (1L<<20) * 10) {
			writel(STDERR, total / (1L<<20));
			write(STDERR, "MB", 2);
		} else if (total >= (1L<<20)) {
			writed(STDERR, (double)total / (double)(1L<<20), 1);
			write(STDERR, "MB", 2);
		} else if (total >= (1L<<10) * 10) {
			writel(STDERR, total / (1L<<10));
			write(STDERR, "KB", 2);
		} else if (total >= (1L << 10)) {
			writed(STDERR, (double)total / (double)(1L<<10), 1);
			write(STDERR, "KB", 2);
		} else {
			writel(STDERR, total);
			write(STDERR, "B", 1);
		}
		write(STDERR, "    \r", 5);
		write(STDOUT, buffer, (size_t)bytesread);
	}
	write(STDERR, "\n", 1);
	if (bytesread < 0) {
		char err[] = "write error";
		write(STDERR, err, sizeof err - 1);
		return EXIT_FAILURE;
	}
	return 0;
}
		

This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/>