Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <limits.h>
- #include <string.h>
- #define MIN(a, b) ((a > b) ? b : a)
- #define MAX(a, b) ((a > b) ? a : b)
- int getFD(const char *const fname, int flags, int perm) {
- int fd = open(fname, flags, perm);
- if (fd < 0) {
- perror("");
- exit(1);
- }
- return fd;
- }
- void closeFD(int fd) {
- if (close(fd) < 0) {
- perror("");
- exit(1);
- }
- }
- int main(int argc, char *argv[]) {
- if (argc != 3) {
- fprintf(stderr, "Wrong usage!\n");
- exit(1);
- }
- int fd1 = getFD(argv[1], O_RDONLY, 0);
- unsigned sof;
- unsigned on1b = 0, on2b = 0, on4b = 0;
- unsigned min = UINT_MAX, max = 0;
- unsigned long long sum = 0;
- while (read(fd1, &sof, 1) > 0) {
- unsigned len, data;
- read(fd1, &len, 1);
- read(fd1, &data, len);
- switch (len) {
- case 1:
- on1b++;
- break;
- case 2:
- on2b++;
- break;
- case 4:
- on4b++;
- break;
- }
- min = MIN(min, data);
- max = MAX(max, data);
- sum += data;
- }
- closeFD(fd1);
- int fd2 = getFD(argv[2], O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
- static char ans[50];
- sprintf(ans, "min: %u\n", min);
- write(fd2, ans, strlen(ans));
- sprintf(ans, "max: %u\n", max);
- write(fd2, ans, strlen(ans));
- sprintf(ans, "avg: %g\n", 1. * sum / (on1b + on2b + on4b));
- write(fd2, ans, strlen(ans));
- sprintf(ans, "1 byte ints: %u\n", on1b);
- write(fd2, ans, strlen(ans));
- sprintf(ans, "2 byte ints: %u\n", on2b);
- write(fd2, ans, strlen(ans));
- sprintf(ans, "4 byte ints: %u\n", on4b);
- write(fd2, ans, strlen(ans));
- close(fd2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement