/*
http://stackoverflow.com/questions/30388085/how-to-use-utf-8-in-c-code/30395420

sudo apt-get install libunistring0 libunistring-dev
gcc utf8test.c -iunistring
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistr.h>
#include <assert.h>

#define SIZE 40

int main(int argc, char **argv)
{
  uint8_t buf[SIZE + 1];
  uint8_t *pat = "привет мир";
  uint8_t str[SIZE + 2];

  /* Make sure program is correctly saved as UTF-8 */
  assert(u8_strcmp("вход", "\320\262\321\205\320\276\320\264") == 0);
  assert(u8_strcmp("выход", "\320\262\321\213\321\205\320\276\320\264") == 0);

  FILE *f1 = fopen("вход", "r");
  FILE *f2 = fopen("выход", "w");

  if (f1 == 0 || f2 == 0)
    {
      perror("Failed to open one or both files");  /* use perror() */
      return(1);
    }

  size_t nbytes;
  if ((nbytes = fread(buf, 1, SIZE, f1) > 0)
    {
      size_t nchars = u8_strlen(buf);

      if (u8_strncmp(buf, pat, nbytes) == 0)
        {
          sprintf(str, "%*s\n", 1+(int)nchars, buf);  /* nchars+1 length specifier for pad */
          fwrite(str, 1, 1+nbytes, f2); /* +1 here too */
        }
      else {
        fprintf(stderr, "%s: %s and %s differ\n", argv[0], buf, pat);
        exit(1);
      }
    }
  else {
    perror("fread");
  }

  fclose(f1);
  fclose(f2);

  return(0);
}