aboutsummaryrefslogtreecommitdiff
path: root/makefs.c
blob: 24d8f6c308cbc758e76684156a1e3f2a1f6dbda3 (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
73
74
75
#include <stdint.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <err.h>
#include <sys/stat.h>
#include <string.h>

#define ANSI_FG_RED "\033[0;31m"
#define ANSI_FG_DEFAULT "\033[0;39m"

int main(int argc, char **argv)
{
  for (int i = 1; i < argc; i++)
    {
      struct stat fileinfo;
      
      if (stat(argv[i], &fileinfo))
	err(-1, "couldn't stat " ANSI_FG_RED "%s" ANSI_FG_DEFAULT,
	    argv[i]);
	
      if (!S_ISREG(fileinfo.st_mode))
	errx(-1, ANSI_FG_RED "%s" ANSI_FG_DEFAULT
	     " is not a regular file.", argv[i]);

      if (fileinfo.st_size > UINT32_MAX)
	errx(-1, ANSI_FG_RED "%s" ANSI_FG_DEFAULT
	     " is too big.", argv[i]);
      
      uint32_t file_size = fileinfo.st_size;
      uint32_t name_size = strlen(argv[i]);
      
      if (fwrite(&name_size, 4, 1, stdout) != 1)
	errx(-1, "error writing to stdout");

      if (printf("%s", argv[i]) != name_size)
	errx(-1, "error writing to stdout");

      for (int j = 0; (j + (name_size & 0b11)) & 0b11; j++)
	if (putchar('\0'))
	  errx(-1, "error writing to stdout");	  
      
      if (fwrite(&file_size, 4, 1, stdout) != 1)
	errx(-1, "error writing to stdout");

      if (fflush(stdout))
	err(-1, "couldn't flush stdout");
      
      pid_t pid;
      int wstatus;
      switch (pid = fork())
	{
	case -1:
	  err(-1, "couldn't fork");
	case 0:
	  if (execlp("cat", "cat", argv[i], NULL))
	    err(-1, "couldn't execute cat");
	default:
	  if (wait(&wstatus) == -1)
	    err(-1, "error waiting for child");

	  if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus))
	    exit(-1);
	}

      for (int j = 0; (j + (file_size & 0b11)) & 0b11; j++)
	if (putchar('\0'))
	  errx(-1, "error writing to stdout");	  
    }
  
  return 0;
}