[Nottingham] Tweaking the orientation flag in a jpeg

Martin Garton martin at stupids.org
Sun Sep 5 20:01:34 UTC 2010


On Fri, 2010-09-03 at 09:31 +0100, Roger Light wrote:

> 
> A good point. I've not needed to use mmap before so it didn't cross my
> mind, but it'd certainly be easier and less prone to error than
> reading the file in.

Okay then, just for fun:

(may contain bugs, not properly tested. may explode your computer, etc.)

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

long offset = 1;
char change_from = 115;
char change_to = 6;

int
main (int argc, char *argv[])
{
  int i;
  int fd;
  int result;
  char *data;
  char *file;

  if (argc == 2)
    {
      file = argv[1];
    }
  else
    {
      printf ("Usage: tweak filename\n");
      exit (EXIT_FAILURE);
    }

  /* Open file */
  fd = open (file, O_RDWR, (mode_t) 0600);
  if (fd == -1)
    {
      perror ("Error opening file");
      exit (EXIT_FAILURE);
    }

  struct stat sb;
  if (fstat (fd, &sb) == -1)
    {
      close (fd);
      exit (EXIT_FAILURE);
    }

  data = mmap (0, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
0);
  if (data == MAP_FAILED)
    {
      close (fd);
      perror ("Error mmapping the file");
      exit (EXIT_FAILURE);
    }

  /* Check value is what we expect */
  if (data[offset] != change_from)
    {
      printf ("Error: Byte at offset %ld is %d not %d.\n", offset,
              data[offset], change_from);
    }
  else
    {
      /* Modify byte */
      data[offset] = change_to;
    }


  if (munmap (data, sb.st_size) == -1)
    {
      perror ("Error mmapping the file");
      close (fd);
      exit (EXIT_FAILURE);
    }

  close (fd);
  return 0;
}


-- 
Martin.





More information about the Nottingham mailing list