1 /***********************************************************************
3 * This software is part of the ast package *
4 * Copyright (c) 1992-2010 AT&T Intellectual Property *
5 * and is licensed under the *
6 * Common Public License, Version 1.0 *
7 * by AT&T Intellectual Property *
9 * A copy of the License is available at *
10 * http://www.opensource.org/licenses/cpl1.0.txt *
11 * (with md5 checksum 059e8cd6165cb4c31e351f2b69388fd9) *
13 * Information and Software Systems Research *
17 * Glenn Fowler <gsf@research.att.com> *
18 * David Korn <dgk@research.att.com> *
20 ***********************************************************************/
25 * reverse the characters or lines of one or more files
29 * dgk@research.att.com
33 static const char usage
[] =
34 "[-?\n@(#)$Id: rev (AT&T Research) 2007-11-29 $\n]"
36 "[+NAME?rev - reverse the characters or lines of one or more files]"
37 "[+DESCRIPTION?\brev\b copies one or more files to standard output "
38 "reversing the order of characters on every line of the file "
39 "or reversing the order of lines of the file if \b-l\b is specified.]"
40 "[+?If no \afile\a is given, or if the \afile\a is \b-\b, \brev\b "
41 "copies from standard input starting at the current offset.]"
42 "[l:line?Reverse the lines of the file.]"
48 "[+0?All files copied successfully.]"
49 "[+>0?One or more files did not copy.]"
51 "[+SEE ALSO?\bcat\b(1), \btail\b(1)]"
58 * reverse the characters within a line
60 static int rev_char(Sfio_t
*in
, Sfio_t
*out
)
63 register char *ep
, *bp
, *cp
;
64 register wchar_t *wp
, *xp
;
71 while(cp
= bp
= sfgetr(in
,'\n',0))
73 ep
= bp
+ (n
=sfvalue(in
)) - 1;
76 w
= roundof(n
+ 1, 1024);
77 if (!(wp
= newof(wp
, wchar_t, w
, 0)))
79 error(ERROR_SYSTEM
|2, "out of space");
88 cp
+= mbconv(cp
, *--xp
);
90 if (sfwrite(out
, bp
, cp
- bp
) < 0)
97 while(cp
= bp
= sfgetr(in
,'\n',0))
99 ep
= bp
+ (n
=sfvalue(in
)) -1;
106 if(sfwrite(out
,cp
,n
)<0)
113 b_rev(int argc
, register char** argv
, void* context
)
117 register int n
, line
=0;
120 cmdinit(argc
, argv
, context
, ERROR_CATALOG
, 0);
121 while (n
= optget(argv
, usage
)) switch (n
)
127 error(2, "%s", opt_info
.arg
);
130 error(ERROR_usage(2), "%s", opt_info
.arg
);
133 argv
+= opt_info
.index
;
134 if(error_info
.errors
)
135 error(ERROR_usage(2),"%s",optusage((char*)0));
141 if(!cp
|| streq(cp
,"-"))
143 else if(!(fp
= sfopen((Sfio_t
*)0,cp
,"r")))
145 error(ERROR_system(0),"%s: cannot open",cp
);
150 line
= rev_line(fp
,sfstdout
,sftell(fp
));
152 line
= rev_char(fp
,sfstdout
);
156 error(ERROR_system(1),"write failed");