【问题标题】:Function to remove newline has no effect?删除换行符的功能没有效果?
【发布时间】:2012-10-21 17:02:00
【问题描述】:

我编写了一个函数来包装 GNU getline() 并删除尾随的换行符,但由于某种原因它没有效果。我是不是做错了什么?

ssize_t readline(char **lineptr, FILE *stream)
{
  size_t len = 0;  // Size of the buffer, ignored.

  ssize_t chars = getline(lineptr, &len, stream);

  if((*lineptr)[chars] == '\n') {
    (*lineptr)[chars] = '\0';
    --chars;
  }

  return chars;
}

它编译和链接没有问题,但换行符不会被空终止符替换。我已经验证 if() 语句正在运行。感谢您的帮助!

【问题讨论】:

  • 刚刚用它来去除换行符,g_strchomp(line)

标签: c


【解决方案1】:

getline 返回读取的字符数。所以你必须使用chars-1 而不是char。

if ((*lineptr)[chars - 1] == '\n') 
  {
      (*lineptr)[chars - 1] = '\0';
      --chars;
  }

ma​​n getline (3)

成功时,getline() 和 getdelim() 返回读取的字符数,包括 > 分隔符,但不 包括终止的空字节。这个值可以用来处理 在读取的行中嵌入空字节。

【讨论】:

    【解决方案2】:

    您要检查并替换最后一个字符,而不是 它之后的那个。

    if ((*lineptr)[chars - 1] == '\n') {
        (*lineptr)[chars - 1] = '\0';
    }
    

    (getline() 返回读取的字符数,就像strlen() 返回字符串的长度一样,不包括终止的 0 字符。)

    【讨论】:

    • @James 没问题。请投票/接受(当您可以这样做时)。
    猜你喜欢
    • 2012-03-22
    • 2018-07-03
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多