ompanion fgetline function which reads from an arbitrary file pointer in C



#include

int fgetline(FILE *fp, char line[], int max)
{
int nch = 0;
int c;
max = max - 1; /* leave room for '\0' */

while((c = getc(fp)) != EOF)
{
if(c == '\n')
break;

if(nch < max)
{
line[nch] = c;
nch = nch + 1;
}
}

if(c == EOF && nch == 0)
return EOF;

line[nch] = '\0';
return nch;
}


Now we could read one line from ifp by calling

char line[MAXLINE];
...
fgetline(ifp, line, MAXLINE);

No comments:

Post a Comment