C文件读取,空白/空行

时间:2012-02-18 16:48:56

标签: c debugging file-io blank-line

直升机,

  if('\t' == input [0] ||'\v' == input [0] ||'\r' == input [0] ||'\n' == input [0] || '\0' == input[0] || '' == input[0])

输入是字符数组:)

这是我在文件中检查空白行的代码行,但它从来没有选中空行例如..

我的代码读取8位十六进制值,我希望在无效(已经排序)或当空行,空白行或EOF时终止。

如果我的文件是这样的话,它可以工作...... 11111111 11111111

^空行上有空格 但如果没有空间它只是打入一个infitie循环,这非常烦人。

#define MAXIN 4096 
  static char input[MAXIN]; 
  char last;
    /*Reading the current line */
  fgets(input, MAXIN, f);;
  if (input[8] == '\r') input[8] = '\0';
  /* First of all check if it was a blank line, i.e. just a '\n' input...*/
  if('\t' == input [0] ||'\v' == input [0] ||'\r' == input [0] ||'\n' == input [0] || '\0' == input[0] || '' == input[0])
  {printf("##EMPTY");return(INERR);}
  if ('\n' == input[0]) return(INERR); 

 if ((sscanf(input,"%8x%c",&result,&last) < 2)) return(INERR);
  if ('\n' != last) return(INERR);  
}

3 个答案:

答案 0 :(得分:2)

您需要检查fgets的返回值。此函数返回NULL以表示“文件结束”。简单地说,试试这个:

if (!fgets(input, MAXIN, f))
    return INERR;

答案 1 :(得分:1)

您可以使用此代码检查该行是否为空:

typedef enum { false = 0, true } bool;

bool isEmptyLine(const char *s) {
  static const char *emptyline_detector = " \t\n";

  return strspn(s, emptyline_detector) == strlen(s);
}

并像这样测试:

fgets(line,YOUR_LINE_LEN_HERE,stdin);
    if (isEmptyLine(line) == false) {
        printf("not ");
    }
printf("empty\n");

答案 2 :(得分:0)

你使用了错误的方法。您必须检查该行是否以'\ n'结尾,以及该行中该字符之前的所有字符是否都不可打印。仅检查第一个字符是不够的。

应该是这样的:

int len = strlen(input);

int isEmpty = 1;
if(input[--len] == '\n')
{
    while (len > 0)
    {
       len--;
       // check here for non printable characters in input[len] 
       // and set isEmpty to 0 if you find any printable chars

    }
}

if(isEmpty == 1)
   // line is empty
相关问题