1

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
jian
  • 4,119
  • 1
  • 17
  • 32
  • If the last return from `fgetc()` is EOF, then simply return 0... Ain't gonna find no more in this file whether it ended with LF or not... – Fe2O3 Oct 08 '22 at 06:09
  • The way you formatted your 2nd code sample is making it really hard for yourself (b is assigned a value if the break isn't executed). – Allan Wind Oct 08 '22 at 06:09
  • 1
    Instead of `return 1` do `return (c != EOF)`. That is, change the definition of `shortread` such that EOF is not considered a short read. – kaylum Oct 08 '22 at 06:09

1 Answers1

1

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

kaylum
  • 13,833
  • 2
  • 22
  • 31