c getline skip blank line

本秂侑毒 提交于 2019-12-07 20:05:36

问题


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?


回答1:


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");
    }

    ..
}



回答2:


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");
    }
...
}


来源:https://stackoverflow.com/questions/13326464/c-getline-skip-blank-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!