dd

C89 implementation of dd
git clone git://ssnf.xyz/dd
Log | Files | Refs

dd.c (1098B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 typedef unsigned char uchar;
      6 typedef unsigned int uint;
      7 
      8 FILE*
      9 efopen(char* path, char* mode)
     10 {
     11 	FILE* f;
     12 
     13 	f = fopen(path, mode);
     14 	if (!f) {
     15 		perror(path);
     16 		exit(1);
     17 	}
     18 	return f;
     19 }
     20 
     21 int
     22 main(int argc, char* argv[])
     23 {
     24 	FILE* in, *out;
     25 	char* buf;
     26 	uint bs, count, n;
     27 
     28 	in = stdin;
     29 	out = stdout;
     30 	bs = 512;
     31 	count = 0;
     32 	for (n = 1; n < argc; ++n) {
     33 		if (!strncmp(argv[n], "if=", 3))
     34 			in = efopen(argv[n] + 3, "r");
     35 		else if (!strncmp(argv[n], "of=", 3))
     36 			out = efopen(argv[n] + 3, "w");
     37 		else if (!strncmp(argv[n], "count=", 6))
     38 			sscanf(argv[n] + 6, "%d", &count);
     39 		else if (!strncmp(argv[n], "bs=", 3)) {
     40 			sscanf(argv[n] + 3, "%d", &bs);
     41 			switch (argv[n][strlen(argv[n])-1]) {
     42 				case 'k':
     43 					bs <<= 10;
     44 					break;
     45 				case 'M':
     46 					bs <<= 20;
     47 					break;
     48 				case 'G':
     49 					bs <<= 30;
     50 			}
     51 		}
     52 	}
     53 	buf = malloc(bs);
     54 	if (!count) {
     55 		for (;n = fread(buf, 1, bs, in);)
     56 			fwrite(buf, 1, n, out);
     57 	} else {
     58 		for (;count--;) {
     59 			fread(buf, 1, bs, in);
     60 			fwrite(buf, 1, bs, out);
     61 		}
     62 	}
     63 	fclose(in);
     64 	fclose(out);
     65 }