BRL-CAD
fgets.c
Go to the documentation of this file.
1 /* F G E T S . C
2  * BRL-CAD
3  *
4  * Copyright (c) 2006-2014 United States Government as represented by
5  * the U.S. Army Research Laboratory.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License
9  * version 2.1 as published by the Free Software Foundation.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this file; see the file named COPYING for more
18  * information.
19  */
20 
21 #include "common.h"
22 
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <math.h>
26 #include <string.h>
27 
28 #include "bu/log.h"
29 
30 char *
31 bu_fgets(char *s, int size, FILE *stream)
32 {
33  int totBytesRead = 0;
34  int isEOF = 0;
35 
36  /* if we are not asked to read anything, just return */
37  if (UNLIKELY(size < 1)) {
38  return s;
39  }
40 
41  /* if the buffer size is one, we have no space (we add a null)
42  * so just return
43  */
44  if (UNLIKELY(size == 1)) {
45  *s = '\0';
46  return s;
47  }
48 
49  /* check for EOF or error */
50  if (feof(stream) || ferror(stream)) {
51  *s = '\0';
52  return (char *)NULL;
53  }
54 
55  /* actually do some reading */
56  while (totBytesRead < size - 1) {
57  int c;
58 
59  c = fgetc(stream);
60  if (c == EOF) {
61  isEOF = 1;
62  break;
63  }
64 
65  s[totBytesRead++] = c;
66 
67  /* check for newline */
68  if (c == '\n') {
69  break;
70  }
71 
72  /* chech for CR */
73  if (c == '\r') {
74 
75  /* check for CR/LF combination */
76  c = fgetc(stream);
77  if (c != '\n') {
78  /* not a CR/LF, so unget the last char */
79  ungetc(c, stream);
80  }
81 
82  break;
83  }
84  }
85 
86  /* add our null */
87  s[totBytesRead] = '\0';
88 
89  if (isEOF && totBytesRead == 0)
90  return (char *)NULL;
91  else
92  return s;
93 }
94 
95 
96 /*
97  * Local Variables:
98  * mode: C
99  * tab-width: 8
100  * indent-tabs-mode: t
101  * c-file-style: "stroustrup"
102  * End:
103  * ex: shiftwidth=4 tabstop=8
104  */
if lu s
Definition: nmg_mod.c:3860
Header file for the BRL-CAD common definitions.
char * bu_fgets(char *s, int size, FILE *stream)
Definition: fgets.c:31
#define UNLIKELY(expression)
Definition: common.h:282