/* * f g e t s . c */ /*)LIBRARY */ #ifdef DOCUMENTATION title fgets Read a string from a file index Read a string from a file synopsis .s.nf char * fgets(buffer, maxbytes, iop) char *buffer; int maxbytes; FILE *iop; char * fgetss(buffer, maxbytes, iop) char *buffer; int maxbytes; FILE *iop; char * gets(buffer) char *buffer; .s.f Description Fgets() reads a string into the buffer from the indicated file. Maxbytes is the maximum number of bytes to read. The string is terminated by a newline character, which is followed by a null. Fgets() normally returns buffer. It returns NULL on end of file or error. If the line being read is maxbytes long or longer, no newline is appended. Gets() reads a line from the standard input device. The terminating newline is replaced by a null byte. Fgetss() is identical to fgets() except that the terminating newline is replaced by a null. (This is compatible with gets(), but fgetss() is not present in the Unix standard library.) Note that fgets keeps the newline, while fgetss() and gets() delete it. To delete the newline after executing fgets(), execute the following: buffer[strlen(buffer) - 1] = 0; Bugs #endif #include #define EOS 0 char * fgetss(buffer, maxbytes, iop) char *buffer; int maxbytes; FILE *iop; /* * Get a line, dump newline at the end */ { extern char *c_fgets(); return (c_fgets(buffer, maxbytes, iop, EOS)); } char * gets(buffer) char *buffer; /* * Get a line from stdin, dump newline at the end */ { extern char *c_fgets(); return (c_fgets(buffer, 512, stdin, EOS)); } char * fgets(buffer, maxbytes, iop) char *buffer; int maxbytes; FILE *iop; /* * Get a line, keep newline at the end */ { extern char *c_fgets(); return (c_fgets(buffer, maxbytes, iop, '\n')); } static char * c_fgets(buffer, maxbytes, iop, terminator) char *buffer; /* buffer to read to */ register int maxbytes; /* sizeof buffer */ FILE *iop; /* Input file */ char terminator; /* For \n at the end. */ /* * Actually get a line */ { register int c; register char *bp; bp = buffer; while (--maxbytes > 0) { if ((c = getc(iop)) == EOS) return (NULL); if ((*bp++ = c) == '\n') { bp[-1] = terminator; break; } } *bp = EOS; return (buffer); }