关于我的C程序跳过空白行的问题

时间:2015-05-04 19:19:52

标签: c pointers line stdout

我有一个完美的main功能。它将指向FILE的指针传递给我的readFile函数,它应该输出文件的数据并删除空行。会发生什么是输出每一行包括空行。我已经彻底检查了我的代码,我似乎无法找到问题。任何帮助将不胜感激!

int
check_whitespace (char *line)
{
  while (*line)
    {
      if (!('\n' == *line || '\t' == *line || ' ' == *line))
        return 0;
      line += 1;
    }
  return 1; /* returns 1 if line is ALL blanks */
}


int
readFile (FILE * fp)
{
  char arrbuff[BUFFSIZE];
  while (fgets (arrbuff, BUFFSIZE, fp) != NULL)
    if (!check_whitespace (arrbuff))
      { /* 0 = goodline */
        fputs (arrbuff, stdout);
      }
  fclose (fp);
}

1 个答案:

答案 0 :(得分:0)

Try changing this line

if (!('\n' == *line || '\t' == *line || ' ' == *line))
    return 0;

in your code to

if (!isspace(*line))
    return 0;

You'll need to add

#include <ctype.h>

I'm guessing you are running under Windows, and each line ends in \r\n and you aren't picking up the \r.

From the man page:

isspace() checks for white-space characters. In the "C" and "POSIX" locales, these are: space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal tab ('\t'), and vertical tab ('\v').

Even if this doesn't fix it, it would make your code far more readable.

Alternatively, for a minimal change:

if (!('\n' == *line || '\t' == *line || ' ' == *line || '\r' == *line))
    return 0;