fgets.c 408 B

123456789101112131415161718192021222324252627
  1. /*
  2. * fgets.c - get a string from a file
  3. */
  4. /* $Id$ */
  5. #include <stdio.h>
  6. char *
  7. fgets(char *s, register int n, register FILE *stream)
  8. {
  9. register int ch;
  10. register char *ptr;
  11. ptr = s;
  12. while (--n > 0 && (ch = getc(stream)) != EOF) {
  13. *ptr++ = ch;
  14. if ( ch == '\n')
  15. break;
  16. }
  17. if (ch == EOF) {
  18. if (feof(stream)) {
  19. if (ptr == s) return NULL;
  20. } else return NULL;
  21. }
  22. *ptr = '\0';
  23. return s;
  24. }