]> git.sur5r.net Git - cc65/blobdiff - libsrc/common/fgets.c
The spans do now contain the size of a span, no longer the end offset.
[cc65] / libsrc / common / fgets.c
index 10c32bde2635b104ba94197b4e07407960c4009e..e65fb4bc8e28ef0849a7acf03bc2a17167574b3c 100644 (file)
 
 
 
-char* fgets (char* s, unsigned size, FILE* f)
+/*****************************************************************************/
+/*                                          Code                                    */
+/*****************************************************************************/
+
+
+
+char* __fastcall__ fgets (char* s, unsigned size, FILE* f)
 {
-    int i, c;
+    unsigned i;
+    int c;
 
-    /* We do not handle the case "size == 0" here */
-    i = 0; --size;
-    while (i < size) {
+    if (size == 0) {
+        /* Invalid size */
+        return (char*) _seterrno (EINVAL);
+    }
+
+    /* Read input */
+    i = 0;
+    while (--size) {
 
                /* Get next character */
-               c = fgetc (f);
-               if (c == -1) {
-                   s [i] = 0;
+               if ((c = fgetc (f)) == EOF) {
+                   s[i] = '\0';
                    /* Error or EOF */
-                   if (f->f_flags & _FERROR) {
-                       /* ERROR */
-                       return 0;
+                   if ((f->f_flags & _FERROR) != 0 || i == 0) {
+                       /* ERROR or EOF on first char */
+                       return 0;
                    } else {
-                       /* EOF */
-               if (i) {
-                   return s;
-               } else {
-                   return 0;
-               }
+                       /* EOF with data already read */
+                break;
            }
                }
 
                /* One char more */
-               s [i++] = c;
+               s[i++] = c;
 
-       /* Stop at end of line */
-       if (c == '\n') {
-           break;
-       }
+       /* Stop at end of line */
+       if (c == '\n') {
+           break;
+       }
     }
 
-    /* Replace newline by NUL */
-    s [i-1] = '\0';
+    /* Terminate the string */
+    s[i] = '\0';
 
     /* Done */
     return s;
@@ -56,4 +63,3 @@ char* fgets (char* s, unsigned size, FILE* f)
 
 
 
-