Skip to content

Instantly share code, notes, and snippets.

@syohex
Created January 10, 2011 04:57
Show Gist options
  • Save syohex/772387 to your computer and use it in GitHub Desktop.
Save syohex/772387 to your computer and use it in GitHub Desktop.
cat2.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void die(const char *s);
static void do_cat_from_stdin(void);
static void do_cat_from_file(const char *path);
static int do_cat(int fd);
int main(int argc, char *argv[])
{
int i;
if (argc < 2) {
do_cat_from_stdin();
}
for (i = 1; i < argc; i++) {
do_cat_from_file(argv[i]);
}
exit(0);
}
static void do_cat_from_stdin(void)
{
if (do_cat(STDIN_FILENO) != 0)
die("STDIN");
}
static void do_cat_from_file(const char *path)
{
int fd;
fd = open(path, O_RDONLY);
if (fd < 0)
die(path);
if (do_cat(fd) != 0)
die(path);
if (close(fd) < 0)
die(path);
}
#define BUFFER_SIZE 2048
static int do_cat(int fd)
{
unsigned char buf[BUFFER_SIZE];
int n;
for (;;) {
n = read(fd, buf, sizeof(buf));
if (n < 0)
return -1;
if (n == 0)
break;
if (write(STDOUT_FILENO, buf, n) < 0)
return -1;
}
return 0;
}
static void die(const char *s)
{
perror(s);
exit(1);
}
#!/bin/sh
if [ -e ./cat2 ]
then
rm -f cat2
fi
gcc -Wall -o cat2 cat2.c
echo From STDIN test
tempfile=`mktemp tmp.XXXXXXXX`
./cat2 < cat2.c > tempfile
TESTNAME="stdin test"
RETVAL=
if cmp -s cat2.c tempfile
then
RETVAL="OK"
else
RETVAL="NG"
fi
echo $TESTNAME : $RETVAL
echo From Command Line
./cat2 cat2.c > tempfile
TESTNAME="command line test"
if cmp -s cat2.c tempfile
then
RETVAL="OK"
else
RETVAL="OK"
fi
echo $TESTNAME : $RETVAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment