Update tail.c

added constant define and also value checking for fname and nlines. not specifying "nlines" resulted in an eval cost exceeded error.
This commit is contained in:
gesslar 2020-09-15 18:00:21 -04:00 committed by Yucong Sun
parent ca289f1b12
commit 432ff0e185

View file

@ -1,3 +1,5 @@
#define TAIL_LINES 11
#ifdef COMPAT_TAIL
/* This version is strictly compatible with the old version */
int tail(string fname) {
@ -22,28 +24,33 @@ int tail(string fname) {
* returns the string, so write(tail(fname)) is needed for strict
* compatibility.
*/
varargs string tail(string fname, int nlines) {
int chunk = nlines * 80;
int offset = file_size(fname);
int num_nl, p, skip;
varargs string tail(string fname, int nlines)
{
int chunk, offset, num_nl, p, skip;
string str = "";
if(nullp(fname)) error("tail: No file name supplied.");
if(nullp(nlines) || nlines < 1) nlines = TAIL_LINES;
chunk = nlines * 80;
offset = file_size(fname);
while (offset > 0 && num_nl <= nlines) {
num_nl = 0;
offset -= chunk;
if (offset < 0) {
chunk += offset; /* negative */
offset = 0;
}
str = read_bytes(fname, offset, chunk) + str;
p = -1;
while (p < sizeof(str)-1 && p = member_array('\n', str, p+1))
num_nl++;
num_nl = 0;
offset -= chunk;
if (offset < 0) {
chunk += offset; /* negative */
offset = 0;
}
str = read_bytes(fname, offset, chunk) + str;
p = -1;
while (p < sizeof(str)-1 && p = member_array('\n', str, p+1))
num_nl++;
}
skip = num_nl - nlines;
p = -1;
while (skip--)
p = member_array('\n', str, p+1);
p = member_array('\n', str, p+1);
return str[p..];
}
#endif