1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include "log.h"
static int needNewline=0;
static void printNewlineIfNeeded(void) {
if (needNewline) {
fprintf(stderr, "\n");
}
needNewline=0;
}
/**
* Print message to the log, if not null
*/
int logprintf(FILE *logfile, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
if(logfile != NULL) {
char buf[9];
struct timeval tv;
int r;
gettimeofday(&tv, NULL);
strftime(buf, sizeof(buf), "%H:%M:%S", localtime(&tv.tv_sec));
fprintf(logfile, "%s.%06ld ", buf, tv.tv_usec);
r= vfprintf(logfile, fmt, ap);
fflush(logfile);
return r;
} else
return -1;
}
/**
* Print message to stdout, adding a newline "if needed"
* A newline is needed if this function has not yet been invoked
* since last statistics printout
*/
int flprintf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
printNewlineIfNeeded();
return vfprintf(stderr, fmt, ap);
}
volatile int quitting = 0;
/**
* Print message to stdout, adding a newline "if needed"
* A newline is needed if this function has not yet been invoked
* since last statistics printout
*/
int fatal(int code, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
if(quitting)
_exit(code);
quitting=1;
printNewlineIfNeeded();
vfprintf(stderr, fmt, ap);
#if 0
assert(0); /* make it easyer to use a debugger to see where this came
* from */
#endif
exit(code);
}
int printLongNum(unsigned long long x) {
/* fprintf(stderr, "%03d ", (int) ( x / 1000000000000LL ));*/
long long divisor;
long long minDivisor;
int nonzero;
char suffix=' ';
if(x > 1000000000000LL) {
minDivisor = 1048576L;
suffix='M';
} else if(x >= 1000000000) {
minDivisor = 1024L;
suffix='K';
} else {
minDivisor = 1;
suffix=' ';
}
divisor = minDivisor * 1000000LL;
nonzero = 0;
while(divisor >= minDivisor) {
int digits;
const char *format;
digits = (int) ((x / divisor) % 1000);
if (nonzero) {
format = "%03d";
} else {
format = "%3d";
}
if (digits || nonzero)
fprintf(stderr, format, digits);
else
fprintf(stderr, " ");
if(digits) {
nonzero = 1;
}
divisor = divisor / 1000;
if(divisor >= minDivisor)
fprintf(stderr, " ");
else
fprintf(stderr, "%c", suffix);
}
needNewline = 1;
return 0;
}
|