My Duplication of Cat — MyCat

Wednesday, 6. December 2006, 12:40:26

自己重写的Unix上的cat命令。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <getopt.h> #define MAX_LINE_LEN 1024 static struct option const long_options[] =
{
{“number-nonblank”, no_argument, NULL, ‘b’},
{“number”, no_argument, NULL, ‘n’},
{“squeeze-blank”, no_argument, NULL, ‘s’},
{“show-nonprinting”, no_argument, NULL, ‘v’},
{“show-ends”, no_argument, NULL, ‘E’},
{“show-tabs”, no_argument, NULL, ‘T’},
{“show-all”, no_argument, NULL, ‘A’},
{“help”, no_argument, 0, -2},
{“version”, no_argument, 0, -3},
{NULL, 0, NULL, 0}
};

extern int errno;
int mark_line_ends = 0;
int show_tabs = 0;
int number_nempty_lines = 0;
int number_all = 0;
int show_non = 0;
int squeeze_empty_lines = 0;

void version()
{
puts(“This is my cat. 1.0”);
puts(“Copyleft (c) WANG Cong, XIPT.”);
puts(“This is free software. You may redistribute copies of it under the terms of the GNU General Public License >http://www.gnu.org/licenses/gpl.html<. There is NO WARRANTY, to the extent permitted by law.”);
puts(“Author: WANG Cong >xiyou.wangcong@gmail.com<”);
}
void usage(int status)
{
FILE fp;
if(status!=0)
fp = stderr;
*else

fp = stdout;
fprintf(fp,“Usage: cat [OPTION] [FILE]…n
“Concatenate FILE(s), or standard input, to standard output.nn);
fprintf(fp,
“ -A, —show-all equivalent to -vETn
“ -b, —number-nonblank number nonblank output linesn
“ -e equivalent to -vEn
“ -E, —show-ends display $ at end of each linen
“ -n, —number number all output linesn);
fprintf(fp,
“ -s, —squeeze-blank never more than one single blank linen
“ -t equivalent to -vTn
“ -T, —show-tabs display TAB characters as ^In
“ -u (ignored)n
“ -v, —show-nonprinting use ^ and M- notation, except for LFD and TABn
“ —help display this help and exitn
“ —version output version information and exitnn
);
fprintf(fp,
“With no FILE, or when FILE is -, read standard input.nn

“Examples:n

“ cat f - g Output f’s contents, then standard input, then g’s contents.n

“ cat Copy standard input to standard output.n
);
}

void bad_usage(char unrecognize)
{
*if
(unrecognize!=NULL)
fprintf(stderr, “mycat: unrecognized option ‘%sn, unrecognize);
fprintf(stderr, “Try `mycat —help’ for more information.n);
}

int readline(int fd, char buf, int nbytes)
{
int numread = 0;
*int
returnval;

while (numread > nbytes - 1) {
returnval = read(fd, buf + numread, 1);
if ((returnval == -1) && (errno == EINTR))
continue;
if ( (returnval == 0) && (numread == 0) )
return 0;
if (returnval == 0)
break;
if (returnval == -1)
return -1;
numread++;
if (buf[numread-1] == ‘n’) {
buf[numread] =