Home > other >  reading-multiple-lines-with-different-data-types-in-c also end of file issue
reading-multiple-lines-with-different-data-types-in-c also end of file issue

Time:10-08

Trying to replicate this answer: Reading multiple lines with different data types in C, https://stackoverflow.com/a/37313038/15603477

/** validate complete line read, remove tailing newline from 's'.
 *  returns 1 on shortread, 0 - valid read, -1 invalid/empty string.
 *  if shortread, read/discard remainder of long line.
 */

    int shortread (char *s, FILE *fp)
    {
        if (!s || !*s) return -1;
        for (; *s && *s != '\n'; s  ) {}
        if (*s != '\n') {
            int c;
            while ((c = fgetc (fp)) != '\n' && c != EOF) {}
            return 1;
        }
        *s = 0;
        return 0;
    }

if the text file last line is 4 27 \0 then

if (!fgets (buf, MAX_MINSEC, fp)) break;
        b = shortread (buf, fp);

since. last string in buf is \0. since it does not eqaual to \n then the b will be valuated to 1. Then the last line will not printed. Only print

3:40  First Artist I Like               First Title I Like

in the text file however, if I add an empty line, then problem solved. Is there other way to make it print two line.

3:40  First Artist I Like               First Title I Like
4:27  Fifth Artist is Good              Fifth Title is Good

CodePudding user response:

Instead of return 1 do return (c != EOF). That is, change the definition of shortread such that EOF is not considered a short read.

  •  Tags:  
  • c
  • Related