c getline skip blank line

2019-05-28 18:25发布

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

I'm using this function to read line line. But i want to know when i'm reading a blank line. Can someone help?

标签: c line getline
2条回答
虎瘦雄心在
2楼-- · 2019-05-28 19:01

You need to define blank line.

Also, because "The getline function reads an entire line from a stream, up to and including the next newline character."

I don't think

strlen(line) == 1

is portable, as Win/DOS and Unix use different convention for EOL. Also, the EOF may occur before an EOL character is done. 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)
}

where is_eol is defined for the platform you are on. This is where you can put in whitespace can be in a blank line, etc.

So you'd get something like:

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");
    }
...
}
查看更多
聊天终结者
3楼-- · 2019-05-28 19:15

so as H2CO3 already mentioned you can use the line 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");
    }

    ..
}
查看更多
登录 后发表回答