2012-04-03 04:10:27 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2012-05-28 17:13:07 +00:00
|
|
|
#include <string.h>
|
2012-05-29 19:02:16 +00:00
|
|
|
#include <libgen.h>
|
2012-04-03 04:10:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
double c2f(double celsius) {
|
|
|
|
return ((9.0 / 5.0) * celsius) + 32.0;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
double f2c(double fahrenheit) {
|
|
|
|
return (5.0 / 9.0) * (fahrenheit - 32.0);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2012-05-29 20:52:13 +00:00
|
|
|
void die_usage(const char *prog, const char *msg) {
|
|
|
|
fprintf(stderr, "Usage: %s <temp>[FC]\n", prog);
|
2012-05-28 17:13:07 +00:00
|
|
|
if (msg != NULL) {
|
2012-05-29 19:02:16 +00:00
|
|
|
fprintf(stderr, "%s\n", msg);
|
2012-05-28 17:13:07 +00:00
|
|
|
}
|
2012-05-29 20:52:13 +00:00
|
|
|
exit(EXIT_FAILURE);
|
2012-04-03 04:10:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
int main(int argc, char * argv[]) {
|
2012-05-29 19:02:16 +00:00
|
|
|
const char * prog = basename(argv[0]);
|
2012-05-28 17:13:07 +00:00
|
|
|
int ret;
|
2012-04-03 04:10:27 +00:00
|
|
|
char msg[255];
|
|
|
|
double temp;
|
2012-05-07 03:31:45 +00:00
|
|
|
char scale = '\0';
|
2012-05-28 17:13:07 +00:00
|
|
|
const char *in_fmt = "%lf%c";
|
|
|
|
const char *out_fmt = "%.2lf%c\n";
|
2012-05-29 19:02:16 +00:00
|
|
|
const char *temp_string;
|
|
|
|
|
|
|
|
if (argc < 2) {
|
2012-05-29 20:52:13 +00:00
|
|
|
die_usage(prog, NULL);
|
2012-05-29 19:02:16 +00:00
|
|
|
}
|
2012-05-28 17:13:07 +00:00
|
|
|
|
|
|
|
if (((int)strlen(argv[1]) == 1) && (argv[1][0] == '-')) {
|
|
|
|
ret = fscanf(stdin, in_fmt, &temp, &scale);
|
|
|
|
} else {
|
2012-05-29 19:02:16 +00:00
|
|
|
temp_string = argv[1];
|
2012-05-28 17:13:07 +00:00
|
|
|
ret = sscanf(temp_string, in_fmt, &temp, &scale);
|
|
|
|
}
|
|
|
|
|
|
|
|
if ((ret == 0) || (ret == EOF)) {
|
2012-05-29 20:52:13 +00:00
|
|
|
die_usage(prog, "No temperature provided!");
|
2012-05-28 17:13:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (ret == 1) {
|
2012-05-29 20:52:13 +00:00
|
|
|
die_usage(prog, "No scale provided!");
|
2012-05-28 17:13:07 +00:00
|
|
|
}
|
2012-04-03 04:10:27 +00:00
|
|
|
|
2012-05-07 03:31:45 +00:00
|
|
|
switch (scale) {
|
|
|
|
case 'C':
|
2012-05-28 17:13:07 +00:00
|
|
|
printf(out_fmt, c2f(temp), 'F');
|
2012-05-07 03:31:45 +00:00
|
|
|
break;
|
|
|
|
case 'F':
|
2012-05-28 17:13:07 +00:00
|
|
|
printf(out_fmt, f2c(temp), 'C');
|
2012-05-07 03:31:45 +00:00
|
|
|
break;
|
|
|
|
default:
|
2012-05-28 17:13:07 +00:00
|
|
|
sprintf(msg, "Unknown scale: '%c'", scale);
|
2012-05-29 20:52:13 +00:00
|
|
|
die_usage(prog, msg);
|
2012-04-03 04:10:27 +00:00
|
|
|
}
|
|
|
|
|
2012-05-29 19:02:16 +00:00
|
|
|
exit(EXIT_SUCCESS);
|
2012-04-03 04:10:27 +00:00
|
|
|
}
|