summaryrefslogtreecommitdiffstats
path: root/test cases/native/8 external program shebang parsing/main.c
blob: 48b080e1f3dd98539c83791383a1067d13d4a3c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>

#ifdef _WIN32
 #include <io.h>
 #include <windows.h>
#else
 #include <unistd.h>
#endif

/* Who cares about stack sizes in test programs anyway */
#define LINE_LENGTH 4096

static int
intrp_copyfile (char * src, char * dest)
{
#ifdef _WIN32
  if (!CopyFile (src, dest, FALSE))
    return 1;
  return 0;
#else
  return execlp ("cp", "cp", src, dest, NULL);
#endif
}

static void
parser_get_line (FILE * f, char line[LINE_LENGTH])
{
  if (!fgets (line, LINE_LENGTH, f))
    fprintf (stderr, "%s\n", strerror (errno));
}

int
main (int argc, char * argv[])
{
  FILE *f = NULL;
  char line[LINE_LENGTH];

  if (argc != 4) {
    fprintf (stderr, "Invalid number of arguments: %i\n", argc);
    goto err;
  }

  if ((f = fopen (argv[1], "r")) == NULL) {
    fprintf (stderr, "%s\n", strerror (errno));
    goto err;
  }

  parser_get_line (f, line);

  if (!line || line[0] != '#' || line[1] != '!') {
    fprintf (stderr, "Invalid script\n");
    goto err;
  }

  parser_get_line (f, line);

  if (!line || strncmp (line, "copy", 4) != 0) {
    fprintf (stderr, "Syntax error: %s\n", line);
    goto err;
  }

  return intrp_copyfile (argv[2], argv[3]);

err:
  fclose (f);
  return 1;
}