#include <stdlib.h>
...
int random;
random = rand();
...
...
float random;
random = (float) rand() / RAND_MAX;
...
...
#define N 42
...
int random;
random = (int)( N * (double)rand() / (RAND_MAX + 1.0) );
...
#include <stdlib.h> #include <time.h>
...
int random;
srand(time(NULL));
random = rand();
...
#include <stdio.h>
...
FILE * fp;
unsigned int random;
if ((fp = fopen("/dev/random","r")) == NULL) {
perror("fopen");
exit(1);
}
fread(&random, sizeof(random), 1, fp);
printf("random number %u from /dev/random\n", random);
fclose(fp);
...
struct tm mk_tm(int year, int month, int day, int hour, int minute, int second)
{
struct tm tmv =
{
.tm_hour = hour, .tm_min = minute, .tm_sec = second,
.tm_year = year - 1900, .tm_mon = month - 1, .tm_mday = day,
.tm_isdst = -1
};
mktime(&tmv);
return tmv;
}
struct tm mk_tm_unfilled(void)
{
return ((struct tm) { -1, -1, -1, -1, -1, -1, -1, -1, -1 });
}
struct tm mk_tm_zero(void)
{
return ((struct tm) { 0, 0, 0, 0, 0, 0, -1, -1, -1 });
}
void show_tm(const struct tm* tmvptr)
{
int year = tmvptr->tm_year > -1 ? tmvptr->tm_year + 1900 : tmvptr->tm_year;
int month = tmvptr->tm_mon > -1 ? tmvptr->tm_mon + 1 : tmvptr->tm_mon;
printf("Y/M/D H:M:S -> %04d/%02d/%02d %02d:%02d:%02d\n",
year, month, tmvptr->tm_mday,
tmvptr->tm_hour, tmvptr->tm_min, tmvptr->tm_sec);
printf("DOW: %02d\nDOY: %02d\nDaylight Saving: %02d\n",
tmvptr->tm_wday, tmvptr->tm_yday, tmvptr->tm_isdst);
fflush(stdout);
}
time_t mktime_utc(struct tm* tmvptr)
{
const char NUL = '\0'; char tzold[32] = {NUL}, tznew[32] = {NUL};
void save_tz(void)
{
char* tz = getenv("TZ"); if (tz != NULL) strcpy(tzold, tz);
}
void restore_tz(void)
{
char* tz = (tzold[0] != NUL) ? strcat(strcpy(tznew, "TZ="), tzold) : "TZ";
putenv(tz);
}
save_tz();
putenv("TZ=UTC");
time_t utc = mktime(tmvptr);
restore_tz();
return utc;
}
time_t mk_date_interval(const char* arg1, ...)
{
static const char EQ = '=', COMMA = ',', NUL = '\0';
static char buffer[16];
char* parse_entry(const char* entry, int* value)
{
char* p = (char*) entry;
while (*p++ != EQ) if (*p == NUL) return NULL;
*value = atoi(p);
p = buffer;
while (*entry != EQ) *p++ = *entry++;
*p = NUL;
return buffer;
}
int getvalue(const char* key)
{
static const char* const TBL = "sec=1,min=60,hou=3600,day=86400,wee=604800";
char* p = (char*) strcasestr(TBL, key);
if (!p) return 0;
while (*p++ != EQ) ;
char* q = p;
while (*q != NUL) if (*q == COMMA) break; else ++q;
memcpy(buffer, p, q - p);
*(buffer + (q - p)) = NUL;
return atoi(buffer);
}
int interval = 0, value; const char* key;
if (!(key = parse_entry(arg1, &value))) return 0;
interval += value * getvalue(key);
const char* arg; va_list ap;
va_start(ap, arg1);
while ((arg = va_arg(ap, const char*)) != NULL)
{
if (!(key = parse_entry(arg, &value))) return 0;
interval += value * getvalue(key);
}
va_end(ap);
return interval;
}
time_t to_epoch(const char* intvltype, double multiple)
{
return (time_t) floor(multiple * get_date_interval_value(intvltype));
}
double from_epoch(const char* intvltype, time_t tv)
{
double interval = get_date_interval_value(intvltype);
return (interval > 0.0) ? tv / interval : 0.0;
}
double get_date_interval_value(const char* intvltype)
{
double interval = 0.0;
switch (*intvltype)
{
case 'd' : interval = strncasecmp(intvltype, "day", 3) == 0 ? 86400.0 : 0.0; break;
case 'h' : interval = strncasecmp(intvltype, "hou", 3) == 0 ? 3600.0 : 0.0; break;
case 'm' : interval = strncasecmp(intvltype, "min", 3) == 0 ? 60.0 : 0.0; break;
case 's' : interval = strncasecmp(intvltype, "sec", 3) == 0 ? 1.0 : 0.0; break;
case 'w' : interval = strncasecmp(intvltype, "wee", 3) == 0 ? 604800.0 : 0.0; break;
}
return interval;
}
int doy(int year, int month, int day)
{
const int BASE = -1; static const int cumdays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
if (month < 1 || month > 12) return -1;
return BASE + cumdays[month - 1] + day + (is_leap_year(year) && month > 2 ? 1 : 0);
}
const char* dayname(int day)
{
static const char* dnams[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
if (day < 0 || day > 6) return NULL;
return dnams[day];
}
bool is_parseable_date(const char* date, const char* fmt, struct tm* tmvptr)
{
static char datebuf[128];
if (strptime(date, fmt, tmvptr) != 0)
{
datebuf[0] = '\1';
return !(strftime(datebuf, sizeof(datebuf), fmt, tmvptr) == 0 && datebuf[0] != '\0');
}
return false;
}
bool is_leap_year(int year)
{
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
bool is_valid_hms(int hour, int minute, int second)
{
if (hour == 24 && minute == 0 && second == 0)
return true;
if (hour > -1 && hour < 24)
if (minute > -1 && minute < 60)
if (second > -1 && second < 60)
return true;
return false;
}
bool is_valid_ymd(int year, int month, int day)
{
static const int mtbl[] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (year < 1970 || year > 2038) return false;
if (month > 0 && month < 13 && day > 0 && day <= mtbl[month]) return true;
if (day == 29 && month == 2 && is_leap_year(year)) return true;
return false;
}
bool is_valid_tm(struct tm* tmvptr)
{
return
is_valid_hms(tmvptr->tm_hour, tmvptr->tm_min, tmvptr->tm_sec) &&
is_valid_ymd(tmvptr->tm_year + 1900, tmvptr->tm_mon + 1, tmvptr->tm_mday) &&
mktime(tmvptr) != -1;
}
const char* mk_fmt_date(const char* fmt, const struct tm* tmvptr)
{
static char datebuf[64];
return (strftime(datebuf, sizeof(datebuf), fmt, tmvptr) == 0) ? NULL : datebuf;
}
double hms_to_frac(int hour, int min, int sec)
{
return (hour * 3600 + min * 60 + sec) / 86400.;
}
void frac_to_hms(double frac, int* hour, int* min, int* sec)
{
int seconds = floor(frac * 86400.);
*hour = seconds / 3600;
*min = (seconds - *hour * 3600) / 60;
*sec = (seconds - (*hour * 3600 + *min * 60));
}
#include <time.h>
int main(void)
{
time_t curtime = time(NULL);
struct tm* locptr = localtime(&curtime);
}
#include <time.h>
#include <sys/time.h>
int main(void)
{
time_t curtime = ({ struct timeval timev; gettimeofday(&timev, NULL); timev.tv_sec; });
struct tm* locptr = localtime(&curtime);
}
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t curtime = time(NULL);
printf("today is %s", ctime(&curtime)); fflush(stdout);
struct tm* locptr = localtime(&curtime);
printf("today is %s", asctime(locptr)); fflush(stdout);
char datebuf[32];
strftime(datebuf, sizeof(datebuf), "%Y-%m-%d", locptr);
printf("today is %s\n", datebuf); fflush(stdout);
printf("today is %04d-%02d-%02d\n",
locptr->tm_year + 1900,
locptr->tm_mon + 1,
locptr->tm_mday);
fflush(stdout);
}
#include <time.h>
#include <stdlib.h>
#include <string.h>
struct tm mk_tm(int year, int month, int day, int hour, int minute, int second);
time_t mktime_utc(struct tm* tmvptr);
int main(void)
{
struct tm tmv = mk_tm(2007, 5, 2, 0, 0, 0);
time_t epoch_seconds_local = mktime(&tmv);
time_t epoch_seconds_utc = mktime_utc(&tmv);
}
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t curtime = time(NULL);
struct tm* locptr = localtime(&curtime);
struct tm* utcptr = gmtime(&curtime);
printf("Dateline: %02d:%02d:%02d-%04d/%02d/%02d\n",
locptr->tm_hour, locptr->tm_min, locptr->tm_sec,
locptr->tm_year + 1900, locptr->tm_mon + 1, locptr->tm_mday);
struct tm loct = *locptr;
printf("Dateline: %02d:%02d:%02d-%04d/%02d/%02d\n",
loct.tm_hour, loct.tm_min, loct.tm_sec,
loct.tm_year + 1900, loct.tm_mon + 1, loct.tm_mday);
fflush(stdout);
}
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <time.h>
time_t mk_date_interval(const char* arg1, ...);
double get_date_interval_value(const char* intvltype);
time_t to_epoch(const char* intvltype, double multiple);
double from_epoch(const char* intvltype, time_t tv);
const char* mk_fmt_date(const char* fmt, const struct tm* tmvptr);
struct tm mk_tm(int year, int month, int day, int hour, int minute, int second);
int main(void)
{
time_t now, difference;
time_t when = now + difference; time_t then = now - difference;
now = time(NULL);
time_t diff1 = to_epoch("day", 2),
diff2 = to_epoch("week", 2);
printf("Today is: %s", ctime(&now));
printf("Two days in the future is: %s", ({ time_t tv = now + diff1; ctime(&tv); }));
printf("Two weeks in the past is: %s", ({ time_t tv = now - diff2; ctime(&tv); }));
printf("\n"); fflush(stdout);
printf("Today is: %s\n", mk_fmt_date("%Y-%m-%d", localtime(&now)));
printf("Two days in the future is: %s\n",
({ time_t tv = now + diff1; mk_fmt_date("%Y-%m-%d", localtime(&tv)); }));
printf("Two weeks in the past is: %s\n",
({ time_t tv = now - diff2; mk_fmt_date("%Y-%m-%d", localtime(&tv)); }));
printf("\n"); fflush(stdout);
time_t birthtime = 96176750;
time_t interval = 5 + 17 * 60 + 2 * 60 * 60 + 55 * 60 * 60 * 24;
then = birthtime + interval;
printf("Then is %s", ctime(&then)); fflush(stdout);
birthtime = ({ struct tm tmv = mk_tm(1973, 1, 18, 3, 45, 50); mktime(&tmv); });
interval = mk_date_interval("day=55", "hou=2", "min=17", "sec=5", NULL);
then = birthtime + interval;
printf("To be precise: %s\n", mk_fmt_date("%H:%M:%S, %Y-%m-%d", localtime(&then)));
fflush(stdout);
}
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
double get_date_interval_value(const char* intvltype);
time_t to_epoch(const char* intvltype, double multiple);
double from_epoch(const char* intvltype, time_t tv);
double hms_to_frac(int hour, int min, int sec);
void frac_to_hms(double frac, int* hour, int* min, int* sec);
struct tm mk_tm(int year, int month, int day, int hour, int minute, int second);
int main(void)
{
time_t recent, earlier;
time_t seconds = recent - earlier;
struct tm tmv1 = mk_tm(1982, 4, 12, 12, 0, 0),
tmv2 = mk_tm(1981, 4, 12, 6, 0, 0);
time_t interval = mktime(&tmv1) - mktime(&tmv2);
double days = from_epoch("day", interval);
printf("An interval of %d epoch seconds is %.3f days\n", interval, days);
time_t bree = 361535725; time_t nat = 96201950;
time_t difference = bree - nat;
printf("There were %d seconds between Nat and Bree\n", difference); fflush(stdout);
bree = ({ struct tm tmv = mk_tm(1981, 6, 16, 20, 35, 25); mktime(&tmv); });
nat = ({ struct tm tmv = mk_tm(1973, 1, 18, 21, 45, 50); mktime(&tmv); });
difference = bree - nat;
printf("There were %d seconds between Nat and Bree\n", difference); fflush(stdout);
printf("There were %.3f seconds between Nat and Bree\n", from_epoch("sec", difference));
printf("There were %.3f minutes between Nat and Bree\n", from_epoch("min", difference));
printf("There were %.3f hours between Nat and Bree\n", from_epoch("hour", difference));
printf("There were %.3f days between Nat and Bree\n", from_epoch("day", difference));
printf("There were %.3f weeks between Nat and Bree\n", from_epoch("week", difference));
fflush(stdout);
double frac = ({ double days = from_epoch("day", difference); days - floor(days); });
int hour, min, sec;
frac_to_hms(frac, &hour, &min, &sec);
printf("Bree came %d days, %d:%d:%d after Nat\n",
(int) from_epoch("day", difference),
hour, min, sec);
fflush(stdout);
}
#include <stdbool.h>
#include <time.h>
#include <stdio.h>
const char* mk_fmt_date(const char* fmt, const struct tm* tmvptr);
struct tm mk_tm(int year, int month, int day, int hour, int minute, int second);
bool is_leap_year(int year);
int doy(int year, int month, int day);
const char* dayname(int day);
int main(void)
{
struct tm* locptr = ({ time_t curtime = time(NULL); localtime(&curtime); });
int day_of_week, day_of_year, week_of_year;
day_of_week = atoi(mk_fmt_date("%w", locptr));
day_of_week = atoi(mk_fmt_date("%u", locptr)); day_of_week = locptr->tm_wday;
day_of_year = atoi(mk_fmt_date("%j", locptr)); day_of_year = locptr->tm_yday; day_of_year = doy(2007, 5, 12);
week_of_year = atoi(mk_fmt_date("%U", locptr)); week_of_year = atoi(mk_fmt_date("%V", locptr)); week_of_year = atoi(mk_fmt_date("%W", locptr));
int year = 1981, month = 6, day = 16;
struct tm tmv = mk_tm(year, month, day, 0, 0, 0);
printf("%d/%d/%d was a %s in week %s\n",
month, day, year, dayname(tmv.tm_wday), mk_fmt_date("%V", &tmv));
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
const char* date = "1998-06-03";
const char* FMT = "%Y-%m-%d";
if (strptime(date, FMT, &tmv) == 0)
{
fputs("Date parse error ...\n", stderr);
return EXIT_FAILURE;
}
struct tm tmv = { 0, 0, 0, 0, 0, 0, -1, -1, -1 };
time_t epoch_seconds = mktime(&tmv);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
const char* date = "1998-06-03";
const char* FMT = "%04d-%02d-%02d";
int year, month, day;
int result = sscanf(date, FMT, &year, &month, &day);
if (result == 0 || result == EOF)
{
fputs("Date parse error ...\n", stderr);
return EXIT_FAILURE;
}
struct tm tmv = { 0, 0, 0, day, month - 1, year - 1900, -1, -1, -1 };
time_t epoch_seconds = mktime(&tmv);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
char date[] = "1998-06-03";
const char* SEP = "-";
int ymd[3]; int i = 0;
char* p = strtok(date, SEP);
while (p)
{
if (i > 2)
{
fputs("Date parse error ...\n", stderr);
return EXIT_FAILURE;
}
ymd[i++] = atoi(p);
p = strtok(NULL, SEP);
}
struct tm tmv = { 0, 0, 0, ymd[2], ymd[1] - 1, ymd[0] - 1900, -1, -1, -1 };
time_t epoch_seconds = mktime(&tmv);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <regex.h>
int main(void)
{
char date[] = "1998-06-03";
const char* PATTERN = "([[:digit:]]{4})-([[:digit:]]{1,2})-([[:digit:]]{1,2})";
regex_t rx;
if (regcomp(&rx, PATTERN, REG_EXTENDED) != 0)
{
fputs("Date parse error [regex compilation failure] ...\n", stderr);
return EXIT_FAILURE;
}
const size_t nmatch = 4;
regmatch_t match[nmatch];
int match_result = regexec(&rx, date, nmatch, match, 0);
regfree(&rx);
if (match_result != 0)
{
fputs("Date parse error [regex mismatch] ...\n", stderr);
return EXIT_FAILURE;
}
const char NUL = '\0';
date[match[1].rm_eo] = NUL;
date[match[2].rm_eo] = NUL;
date[match[3].rm_eo] = NUL;
int year = atoi((char*) date + match[1].rm_so);
int month = atoi((char*) date + match[2].rm_so);
int day = atoi((char*) date + match[3].rm_so);
struct tm tmv = { 0, 0, 0, day, month - 1, year - 1900, -1, -1, -1 };
time_t epoch_seconds = mktime(&tmv);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
char date[] = "1998-06-03";
const char NUL = '\0', SEP = '-';
char *p = date, *q = date;
int year, month, day;
while (*p++ != SEP) ; *p = NUL; year = atoi(q); q = ++p;
while (*p++ != SEP) ; *p = NUL; month = atoi(q); q = ++p;
while (*p++ != NUL) ; day = atoi(q);
struct tm tmv = { 0, 0, 0, day, month - 1, year - 1900, -1, -1, -1 };
time_t epoch_seconds = mktime(&tmv);
}
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
struct tm mk_tm(int year, int month, int day, int hour, int minute, int second);
struct tm mk_tm_unfilled(void);
struct tm mk_tm_zero(void);
void show_tm(const struct tm* tmvptr);
bool is_parseable_date(const char* date, const char* fmt, struct tm* tmvptr);
bool is_leap_year(int year);
bool is_valid_hms(int hour, int minute, int second);
bool is_valid_ymd(int year, int month, int day);
bool is_valid_tm(struct tm* tmvptr);
int main(void)
{
const char* FMT = "%Y/%m/%d";
struct tm tmv = mk_tm_zero();
char datebuf[128];
do
{
fputs("Enter a date in YYYY/MM/DD form: ", stdout); fflush(stdout);
fgets(datebuf, sizeof(datebuf), stdin);
if (is_parseable_date(datebuf, FMT, &tmv) && is_valid_tm(&tmv))
break;
fputs("Bad date string - try again\n\n", stdout); fflush(stdout);
} while (true);
show_tm(&tmv);
}
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t curtime = time(NULL);
printf("%s", ctime(&curtime)); fflush(stdout);
}
#include <stdio.h>
#include <time.h>
int main(void)
{
struct tm* curtmptr = ({ time_t curtime = time(NULL); localtime(&curtime); });
printf("%s", asctime(curtmptr)); fflush(stdout);
}
#include <stdio.h>
#include <time.h>
struct tm mk_tm(int year, int month, int day, int hour, int minute, int second);
int main(void)
{
struct tm* curtmptr = ({ time_t curtime = time(NULL); localtime(&curtime); });
const char* fmt = "%Y/%m/%d";
char datebuf[32];
strftime(datebuf, sizeof(datebuf), fmt, curtmptr);
printf("%s\n", datebuf); fflush(stdout);
struct tm curtm = mk_tm(2007, 5, 4, 0, 0, 0);
strftime(datebuf, sizeof(datebuf), fmt, &curtm);
printf("%s\n", datebuf); fflush(stdout);
printf("%04d/%02d/%02d\n", curtmptr->tm_year + 1900, curtmptr->tm_mon + 1, curtmptr->tm_mday);
fflush(stdout);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const char* mk_fmt_date(const char* fmt, const struct tm* tmvptr);
const char* mk_fmt_date_r(const char* fmt, const struct tm* tmvptr, char* datebuf, size_t bufsize);
const char* mk_fmt_date_a(const char* fmt, const struct tm* tmvptr);
int main(void)
{
struct tm* locptr = ({ time_t curtime = time(NULL); localtime(&curtime); });
printf("%s\n", mk_fmt_date("%Y/%m/%d", locptr)); fflush(stdout);
const size_t BUFSIZE = 32; char buffer[BUFSIZE];
printf("%s\n", mk_fmt_date_r("%Y/%m/%d", locptr, buffer, BUFSIZE)); fflush(stdout);
const char* bptr = mk_fmt_date_a("%Y/%m/%d", locptr);
printf("%s\n", bptr); fflush(stdout);
free(bptr); bptr = NULL;
const char* bptrf;
free(((bptrf = mk_fmt_date_a("%Y/%m/%d", locptr)), printf("%s\n", bptrf), fflush(stdout), bptrf));
bptrf = NULL;
({ const char* bptr = mk_fmt_date_a("%Y/%m/%d", locptr); printf("%s\n", bptr); fflush(stdout); free(bptr); });
}
const char* mk_fmt_date(const char* fmt, const struct tm* tmvptr)
{
static char datebuf[64];
return (strftime(datebuf, sizeof(datebuf), fmt, tmvptr) == 0) ? NULL : datebuf;
}
const char* mk_fmt_date_r(const char* fmt, const struct tm* tmvptr, char* datebuf, size_t bufsize)
{
return (strftime(datebuf, bufsize, fmt, tmvptr) == 0) ? NULL : datebuf;
}
const char* mk_fmt_date_a(const char* fmt, const struct tm* tmvptr)
{
static const size_t MAXBUFSIZE = 256;
size_t bufsize = strftime(NULL, MAXBUFSIZE, fmt, tmvptr) + 1;
char* datebuf = (bufsize == 0) ? NULL : (char*) malloc(bufsize);
return (datebuf != NULL && (strftime(datebuf, bufsize, fmt, tmvptr) > 0)) ? datebuf : NULL;
}
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t start = time(NULL);
time_t finish = time(NULL);
printf("Elapsed time %.9f seconds\n", difftime(finish, start)); fflush(stdout);
}
#include <stdio.h>
#include <sys/time.h>
int main(void)
{
struct timeval start, finish;
gettimeofday(&start, NULL);
gettimeofday(&finish, NULL);
double elapsed = finish.tv_sec - start.tv_sec + (finish.tv_usec - start.tv_usec) / 1.e6;
printf("Elapsed time %.9f seconds\n", elapsed); fflush(stdout);
}
#include <stdio.h>
#include <time.h>
int main(void)
{
clock_t start = clock();
clock_t finish = clock();
double proctime = ((double) (finish - start)) / CLOCKS_PER_SEC;
printf("Processor time %.9f seconds\n", proctime); fflush(stdout);
}
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
int main(void)
{
const long CLOCK_TICKS = sysconf(_SC_CLK_TCK);
struct tms st_cpu, en_cpu;
clock_t st_time = times(&st_cpu);
clock_t en_time = times(&en_cpu);
printf("Processor Time (seconds):\n\tReal Time: %.9f, User Time %.9f, System Time %.9f\n",
difftime(en_time, st_time) / CLOCK_TICKS,
difftime(en_cpu.tms_utime, st_cpu.tms_utime) / CLOCK_TICKS,
difftime(en_cpu.tms_stime, st_cpu.tms_stime) / CLOCK_TICKS);
fflush(stdout);
}
#include <stdio.h>
#include <sys/time.h>
int main(void)
{
struct timeval start, finish;
gettimeofday(&start, NULL);
printf("Type in some text, press ENTER when done: "); fflush(stdout);
char line[80];
fgets(line, sizeof(line), stdin);
gettimeofday(&finish, NULL);
double elapsed = finish.tv_sec - start.tv_sec + (finish.tv_usec - start.tv_usec) / 1.e6;
printf("You took %.9f seconds\n", elapsed); fflush(stdout);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
void sort(double array[], int size);
int main(void)
{
struct timeval start, finish;
double elapsed = 0.0;
const int SIZE = 500, NUMBER = 100;
double array[SIZE];
srand(time(NULL));
for (int i = 0; i < NUMBER; ++i)
{
for (int j = 0; j < SIZE; ++j) array[j] = rand();
gettimeofday(&start, NULL);
sort(array, SIZE);
gettimeofday(&finish, NULL);
elapsed = elapsed + (finish.tv_sec - start.tv_sec + (finish.tv_usec - start.tv_usec) / 1.e6);
}
printf("On average, sorting %d random numbers took %.9f seconds\n", SIZE, elapsed / NUMBER);
fflush(stdout);
}
void sort(double array[], int size)
{
int cmp(const void* lp, const void* rp)
{
const double* lpv = (const double*) lp;
const double* rpv = (const double*) rp;
return (*lpv > *rpv) - (*lpv < *rpv);
}
qsort(array, size, sizeof(array[0]), cmp);
}
#include <time.h>
void busywait(double seconds);
int main(void)
{
busywait(0.25);
}
void busywait(double seconds)
{
double elapsed;
clock_t start = clock();
do { elapsed = ((double) (clock() - start)) / CLOCKS_PER_SEC; } while (elapsed < seconds);
}
#include <signal.h>
#include <unistd.h>
void alarmSec(long sec);
int main(void)
{
alarmSec(1);
}
void alarmSec(long sec)
{
static void sig_alrm(int signo) {}
if (signal(SIGALRM, sig_alrm) == SIG_ERR) return;
alarm(sec);
pause();
alarm(0);
}
#include <unistd.h>
#include <sys/time.h>
void sleepSec(long sec);
void sleepMicroSec(long usec);
void sleepNanoSec(long nsec);
int main(void)
{
sleepSec(1);
sleep(1);
sleepMicroSec(250000);
sleepNanoSec(250000);
}
void sleepSec(long sec)
{
nanosleep(&((const struct timespec) { sec, 0 }), NULL);
}
void sleepMicroSec(long usec)
{
nanosleep(&((const struct timespec) { usec / 1000000L, usec % 1000000L * 1000000L }), NULL);
}
void sleepNanoSec(long nsec)
{
nanosleep(&((const struct timespec) { 0, nsec }), NULL);
}
#include <unistd.h>
#include <sys/time.h>
void sleepAbsSec(long sec);
void sleepAbsMicroSec(long usec);
int main(void)
{
sleepAbsSec(1);
sleepAbsMicroSec(250000);
}
void sleepAbsSec(long sec)
{
select(0, NULL, NULL, NULL, &((struct timeval) { sec, 0 }));
}
void sleepAbsMicroSec(long usec)
{
select(0, NULL, NULL, NULL, &((struct timeval) { usec / 1000000L, usec % 1000000L }));
}
#define _GNU_SOURCE
#include <search.h> #include <string.h>#include <stdio.h>#include <stdlib.h>
#define TAB 4
...
struct hsearch_data hash;
size_t max_element = 42;
...
char * food[] = { "Apple",
"Banana",
"Lemon",
"Carrot"
};
char * color[] = { "red",
"yellow",
"yellow",
"orange"
};
memset( &hash, 0, sizeof(hash) );
if( hcreate_r(max_element, &hash) == 0 ) {
perror("hcreate_r");
exit(1);
}
hdestroy_r( &hash );
...
...
void hash_add_element(char * elmt_key,
char * elmt_data,
struct hsearch_data * table) {
ENTRY item;
ENTRY * ret;
item.key = strdup(elmt_key);
item.data = strdup(elmt_data);
if( hsearch_r(item, ENTER, &ret, table) == 0 ) {
perror("hsearch_r");
exit(1);
}
return;
}
...
ENTRY entry;
ENTRY * found;
int i;
hash_add_element(food[0], color[0], &hash);
hash_add_element(food[1], color[1], &hash);
hash_add_element(food[2], color[2], &hash);
hash_add_element(food[3], color[3], &hash);
fprintf(stdout, "Known foods:\n");
for( i = 0; i < TAB; i++ ) {
entry.key = food[i];
hsearch_r( entry, FIND, &found, &hash );
fprintf(stdout, "%s\n", found->key);
free(found->key);
free(found->data);
}
...
# Known foods:
# Apple
# Banana
# Lemon
# Carrot
...
entry.key = "Martini";
if( hsearch_r( entry, FIND, &found, &hash ) != 0 )
else
...
#include <stdio.h>
#include <string.h> #include <errno.h>
...
FILE * fp;
if( (fp = fopen(filename, mode)) == NULL )
fprintf( stderr, "Couldn't open %s for reading : %s\n",
filename,
strerror(errno) );
...
#include <stdio.h>
...
FILE * file;
file = tmpfile();
...
#include <stdio.h> #include <stdlib.h>
...
int fd;
char template[20];
strcpy( template, "tmp/XXXXXX" );
fd = mkstemp( template );
if( fd < 0 ) {
perror( mkstemp );
exit( 1 );
}
remove( template );
...
#include <stdio.h> #include <stdlib.h>
#include <unistd.h> #include <fcntl.h> #include <sys/stat.h>
#include <sys/types.h>
...
char * tmpname = NULL;
int fd;
while(1) {
tmpname = tempnam( NULL, NULL );
if( tmpname == NULL ) {
perror( "tempname" );
exit(1);
}
fd = open( tmpname, O_CREAT | O_EXCL | O_RDWR, 0600 );
unlink( tmpname );
free( tmpname );
if( fd < 0 )
perror( "open" );
else
break;
}
...
#include <stdio.h>
#include <stdlib.h> #include <string.h> #include <errno.h>
...
char file[100] = argv[1]; char * command;
command = malloc( (strlen("wc -l ") + 1) + (strlen(file) + 1) );
sprintf(command, "%s %s", "wc -l", argv[1]);
system(command);
FILE * message;
if( (message = popen(command, "r")) == NULL ) {
fprintf(stderr, "error popen %d\n", errno);
exit(1);
}
char wc_output[100];
fgets(wc_output, sizeof wc_output, message);
fprintf(stdout, "%s", wc_output);
pclose(message);
free(command);
...
#include <stdio.h>
...
char file[100] = argv[1]; FILE * fp;
if( (fp = fopen( file, "r" )) == NULL ) {
perror("fopen");
exit(1);
}
int line = 0;
char ch;
while ( (ch = getc(fp)) != EOF )
if (ch == '\n')
line++;
fprintf(stdout, "number of lines : %d\n", line );
fclose(fp);
...
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> #include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
...
char file[100] = argv[1]; int fd;
fd = open(file, O_RDONLY);
size_t size;
size = lseek(fd, 0, SEEK_END );
char * buffer;
buffer = malloc(size);
lseek(fd, 0, SEEK_SET);
if( (read(fd, buffer, size)) != size ) {
perror("read");
exit(1);
}
close(fd);
int line = 0;
int i;
for( i = 0; i < size; i++ ) {
if(buffer[i] == '\n')
line++;
}
free(buffer);
fprintf(stdout, "number of lines : %d\n", line );
...
#include <stdio.h> #include <unistd.h> #include <sys/stat.h>
...
struct stat entry;
if( stat("/usr/bin/vi", &entry) < 0 )
perror("");
if( S_ISREG(entry.st_mode) )
fprintf( stderr, "file\n" );
...
#include <stdio.h> #include <unistd.h> #include <sys/stat.h>
...
struct stat entry;
if( stat("/usr/bin", &entry) < 0 )
perror("");
if( S_ISDIR( entry.st_mode) )
fprintf( stderr, "directory\n" );
...
#include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h>
...
struct stat entry;
int fd; FILE * fp;
if((fd = open("/etc/group", O_RDONLY)) < 0)
perror("");
if( fstat(fd, &entry) < 0 )
perror("");
if((fp = fdopen(fd, "r" )) == NULL ) perror("");
...
#include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h>
...
struct stat entry;
time_t ctime;
off_t size;
if( stat("/usr/bin/vi", &entry) < 0 )
perror("");
ctime = entry.st_ctime;
size = entry.st_size;
...
#include <stdio.h>
#include <dirent.h> #include <sys/types.h>
...
DIR * dir;
struct dirent * entry;
dir = opendir("/usr/bin");
if( dir == NULL )
perror("");
while((entry = readdir(dir)) != NULL)
fprintf(stdout, "Inside /usr/bin is something called %s\n", entry->d_name);
fprintf(stdout, "\n");
closedir(dir);
...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h>
...
char * dir, * file, * ext;
char * tmp_dirname, * tmp_file;
char * path = "/usr/lib/libc.a";
tmp_dirname = strdup(path);
tmp_file = strdup(path);
dir = dirname(tmp_dirname);
file = basename(tmp_file);
ext = strrchr(path, '.');
fprintf(stdout, "dir is %s, file is %s, ext is %s\n", dir, file, ext);
free(tmp_file);
free(tmp_dirname);
...
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h>
...
char * file, * dir, * tmp_file, * tmp_dirname;
char * path = "/usr/lib/libc.a";
tmp_file = strdup( path );
tmp_dirname = strdup( path );
dir = dirname( tmp_dirname );
file = basename( tmp_file );
fprintf( stdout, "dir is %s, file is %s\n", dir, file );
free(tmp_dirname);
free(tmp_file);
...
#include <stdio.h> #include <stdlib.h> #include <string.h>
typedef struct Pathname_ {
char * dirname;
char * filename;
char * extension;
}Pathname;
void fileparse( const char * path, Pathname * split_path) {
char * tmp_path, * ptr, * extension;
tmp_path = strdup(path);
ptr= strrchr( tmp_path, '/');
*ptr = '\0';
ptr++;
split_path->dirname = strdup(tmp_path);
split_path->filename = malloc(strlen(ptr) + 1);
strcpy(split_path->filename, ptr);
extension = strrchr(path, '.'); after the last '.'
split_path->extension = strdup(extension);
free(tmp_path);
return;
}
int main( int argc, char * argv[] ) {
Pathname fparsed;
char * path = "/usr/lib/libc.a";
fileparse(path, &fparsed);
fprintf(stdout, "dir is %s, file is %s, ext is %s\n",
fparsed.dirname,
fparsed.filename,
fparsed.extension);
free(fparsed.dirname);
free(fparsed.filename);
free(fparsed.extension);
return 0;
}
char * extension(const char * path){
char * ext;
ext = strrchr(path, '.');
if(ext == NULL)
return NULL;
return ext;
}
#include <stdio.h>
static int greeted = 0;
int howManyGreetings(void);
void hello(void);
int main(void)
{
hello();
int greetings = howManyGreetings();
printf("bye there!, there have been %d greetings so far\n", greetings);
}
int howManyGreetings(void)
{
return greeted;
}
void hello(void)
{
printf("high there!, this function has been called %d times\n", ++greeted);
}
#include <math.h>
double hypotenuse(double side1, double side2);
int main(void)
{
double diag = hypotenuse(3.0, 4.0);
}
double hypotenuse(double side1, double side2)
{
return sqrt(pow(side1, 2.0) + pow(side2, 2.0));
}
#include <math.h>
double hypotenuse(double sidearr[]);
int main(void)
{
double sidearr[] = {3.0, 4.0};
double diag = hypotenuse(sidearr);
}
double hypotenuse(double sidearr[])
{
return sqrt(pow(sidearr[0], 2.0) + pow(sidearr[1], 2.0));
}