Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Tuenti Contest
- * Challenge 14 - Colors
- * Author: Pedro Antonio Pardal Jimena
- * Email: pardal@alu.uma.es
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <string.h>
- struct rgb24
- {
- unsigned char b, g, r;
- } __attribute__((packed));
- struct bmp
- {
- /* BITMAPFILEHEADER */
- uint16_t bfType;
- uint32_t bfSize;
- uint16_t bfReserved1;
- uint16_t bfReserved2;
- uint32_t bfOffBits;
- /* BITMAPINFOHEADER */
- uint32_t biSize;
- uint32_t biWidth;
- uint32_t biHeight;
- uint16_t biPlanes;
- uint16_t biBitCount;
- uint32_t biCompression;
- uint32_t biSizeImage;
- uint32_t biXPelsPerMeter;
- uint32_t biYPelsPerMeter;
- uint32_t biClrUsed;
- uint32_t biClrImportant;
- struct rgb24 data[];
- } __attribute__((packed));
- static struct bmp* read_image()
- {
- int fd;
- int longitud;
- struct bmp *img;
- struct stat stbuf;
- if ((fd = open("trabaja.bmp", O_RDONLY)) == -1)
- {
- perror("open");
- exit(-1);
- }
- if (fstat(fd, &stbuf) == -1) {
- perror("fstat");
- exit(-1);
- }
- longitud = stbuf.st_size;
- if ((img = (struct bmp *)mmap((caddr_t) 0, longitud, PROT_READ, MAP_SHARED,
- fd, 0)) == MAP_FAILED)
- {
- perror("mmap");
- exit(-1);
- }
- close(fd);
- return img;
- }
- static void close_image(struct bmp *img)
- {
- munmap(img, img->bfSize);
- }
- static int compute_sum(struct bmp *img, char color, int line)
- {
- int i, base, sum;
- base = (img->biHeight - line - 1) * img->biWidth;
- sum = 0;
- for (i = 0; i < img->biWidth; i++)
- {
- switch (color)
- {
- case 'R':
- sum += img->data[base + i].r;
- break;
- case 'G':
- sum += img->data[base + i].g;
- break;
- case 'B':
- sum += img->data[base + i].b;
- break;
- }
- }
- return sum + 1;
- }
- #define BUFFER_SIZE 0x100
- int main(int argc, char *argv[])
- {
- struct bmp *img;
- int i;
- char buffer[BUFFER_SIZE];
- char *tok;
- char color;
- int line;
- int sum;
- img = read_image();
- while (fgets(buffer, BUFFER_SIZE, stdin) != NULL)
- {
- color = buffer[0];
- line = atoi(&buffer[1]);
- sum = compute_sum(img, color, line);
- fprintf(stdout, "%d\n", sum);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement