Skip to content

Instantly share code, notes, and snippets.

@monzou
Created May 14, 2011 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monzou/972232 to your computer and use it in GitHub Desktop.
Save monzou/972232 to your computer and use it in GitHub Desktop.
cat w/ system call
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void do_cat(const int fd, const char *path);
static void die(const char *s);
int main(int argc, char const *argv[])
{
if (argc < 2) {
do_cat(STDIN_FILENO, "STDIN");
} else {
int i;
for (i = 1; i < argc; i++) {
char *path = (char*) argv[i];
do_cat(open(path, O_RDONLY), path);
}
}
exit(0);
}
#define BUFFER_SIZE 2048
static void do_cat(const int fd, const char *path)
{
if (fd < 0) {
die(path);
}
unsigned char buf[BUFFER_SIZE];
int n;
for (;;) {
n = read(fd, buf, sizeof buf);
if (n < 0) {
die(path);
}
if (n == 0) {
break;
}
if (write(STDOUT_FILENO, buf, n) < 0) {
die(path);
}
}
if (close(fd) < 0) {
die(path);
}
}
static void die(const char *s)
{
perror(s);
exit(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment