C skip empty getline string

while(getline (&line, &line_size, f) != -1){}  

I use this function to read a string. But I want to know when I read an empty line. Can anyone help?

+1
source share
2 answers

since the already mentioned H2CO3 you can use the string length for this:

while (getline (&line, &line_size, f) != -1) {

    if (strlen(line) == 1) {
        printf("H2CO3 spotted a blank line\n");
    }

    /* or alternatively */
    if ('\n' == line[0]) {
        printf("Ed Heal also spotted the blank line\n");
    }

    ..
}
+3
source

You need to specify an empty string.

Also, since "the getline function reads an entire line from the stream, up to the next newline character."

I do not think that

strlen(line) == 1

is portable since Win / DOS and Unix use different conventions for EOL. In addition, EOF can occur before the EOL character is executed. So, really, you need to define a function, maybe something like

int is_blank_line(char *line, int line_size)
{
   return line_size == 0 || is_eol(line)
}

is_eol , . ..

, - :

int is_eol(char *line)
{
...
     return result;
}
...
int is_blank_line(char *line, int line_size)
{
  return line_size == 0 || is_eol(line)
}
...
while (getline (&line, &line_size, f) != -1) {
    if (is_blank_line(line, line_size)) {
        printf("blank line spotted\n");
    }
...
}
0

All Articles