123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- #define PROGRAM_NAME "mtd-utils"
- #include <sys/time.h>
- #include <sys/types.h>
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include "common.h"
- static int get_multiplier(const char *str)
- {
- if (!str)
- return 1;
-
- while (*str == ' ' || *str == '\t')
- str += 1;
- if (!strcmp(str, "KiB"))
- return 1024;
- if (!strcmp(str, "MiB"))
- return 1024 * 1024;
- if (!strcmp(str, "GiB"))
- return 1024 * 1024 * 1024;
- return -1;
- }
- long long util_get_bytes(const char *str)
- {
- char *endp;
- long long bytes = strtoull(str, &endp, 0);
- if (endp == str || bytes < 0) {
- fprintf(stderr, "incorrect amount of bytes: \"%s\"\n", str);
- return -1;
- }
- if (*endp != '\0') {
- int mult = get_multiplier(endp);
- if (mult == -1) {
- fprintf(stderr, "bad size specifier: \"%s\" - "
- "should be 'KiB', 'MiB' or 'GiB'\n", endp);
- return -1;
- }
- bytes *= mult;
- }
- return bytes;
- }
- void util_print_bytes(long long bytes, int bracket)
- {
- const char *p;
- int GiB = 1024 * 1024 * 1024;
- int MiB = 1024 * 1024;
- int KiB = 1024;
- if (bracket)
- p = " (";
- else
- p = ", ";
- printf("%lld bytes", bytes);
- if (bytes > GiB)
- printf("%s%lld.%lld GiB", p,
- bytes / GiB, bytes % GiB / (GiB / 10));
- else if (bytes > MiB)
- printf("%s%lld.%lld MiB", p,
- bytes / MiB, bytes % MiB / (MiB / 10));
- else if (bytes > KiB && bytes != 0)
- printf("%s%lld.%lld KiB", p,
- bytes / KiB, bytes % KiB / (KiB / 10));
- else
- return;
- if (bracket)
- printf(")");
- }
- int util_srand(void)
- {
- struct timeval tv;
- struct timezone tz;
- unsigned int seed;
-
- if (gettimeofday(&tv, &tz))
- return -1;
- seed = (unsigned int)tv.tv_sec;
- seed += (unsigned int)tv.tv_usec;
- seed *= getpid();
- seed %= RAND_MAX;
- srand(seed);
- return 0;
- }
|