/* read the next line of the file into
* the buffer of size n that p points to.
* Successive calls to readline() read the file
* from front to back.
*/
readline(file,p,n) int file; char *p; int n;
{
int c;
int k;
k=0;
while (1) {
c=sysrdch(file);
if (c==ERR) {
return(ERR);
}
if (c==EOF) {
/* ignore line without CR */
return (EOF);
}
if (c==CR) {
return(k);
}
if (k<n) {
/* move char to buffer */
*p++=c;
}
/* always bump count */
k++;
}
}
/* push (same as write) line to end of file.
* line is in the buffer of size n that p points to.
* lines written by this routine may be read by
* either readline() or popline().
*/
pushline(file,p,n) int file; char *p; int n;
{
/* write all but trailing CR */
while ((n--)>0) {
if (syspshch(*p++,file)==ERR) {
return(ERR);
}
}
/* write trailing CR */
return(syspshch(CR,file));
}
/* pop a line from the back of the file.
* the line should have been pushed using pushline().
*/
popline(file,p,n) int file; char *p; int n;
{
int c;
int k, kmax, t;
/* first char must be CR */
c=syspopch(file);
if (c==EOF) {
/* at START of file */
return(EOF);
}
if (c==CR) {
/* put into buffer */
*p++=CR;
k=1;
}
else {
syserr("popline: missing CR");
return(ERR);
}
/* pop line into buffer in reverse order */
while (1) {
c=syspopch(file);
if (c==ERR) {
return(ERR);
}
if (c==EOF) {
break;
}
if (c==CR) {
/* this ends ANOTHER line */
/* push it back */
if (syspshch(CR,file)==ERR) {
return(ERR);
}
break;
}
/* non-special case */
if (k<n) {
/* put into buffer */
*p++=c;
}
/* always bump count */
k++;
}
/* remember if we truncated the line */
kmax=k;
/* reverse the buffer */
k=min(k,n-1);
t=0;
while (k>t) {
/* swap p[t], p[k] */
c=p[k];
p[k]=p[t];
p[t]=c;
k--;
t++;
}
return(kmax);
}