examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

cat.c (948B)


      1 #include <unistd.h>
      2 #include <sys/stat.h>
      3 #include <fcntl.h>
      4 
      5 #include <stdlib.h>
      6 #include <stdio.h>
      7 #include <string.h>
      8 
      9 static void die(char const* str)
     10 {
     11 	perror(str);
     12 	exit(EXIT_FAILURE);
     13 }
     14 
     15 static void do_write(char const* buf, ssize_t size)
     16 {
     17 	while (size)
     18 	{
     19 		ssize_t n = write(1, buf, size);
     20 		if (n < 0)
     21 			die("write");
     22 
     23 		buf += n;
     24 		size -= n;
     25 	}
     26 }
     27 
     28 int main(int argc, char const* argv[])
     29 {
     30 	struct stat s;
     31 	int fds[argc];
     32 
     33 	--argc;
     34 	++argv;
     35 
     36 	if (argc == 0)
     37 	{
     38 		argv[0] = "-";
     39 		++argc;
     40 	}
     41 
     42 	for (int i = 0; i < argc; ++i)
     43 	{
     44 		char const* path = argv[i];
     45 
     46 		if (!strcmp("-", path))
     47 			fds[i] = 0;
     48 		else if (stat(path, &s))
     49 			die("stat");
     50 		else if ((fds[i] = open(path, O_RDONLY)) < 0)
     51 			die("open");
     52 	}
     53 
     54 	for (int i = 0; i < argc; ++i)
     55 	{
     56 		char buf[4096];
     57 		ssize_t n;
     58 		int fd = fds[i];
     59 
     60 		while ((n = read(fd, buf, sizeof(buf))) > 0)
     61 			do_write(buf, n);
     62 		if (n < 0)
     63 			die("read");
     64 
     65 		close(fd);
     66 	}
     67 	return EXIT_SUCCESS;
     68 }