简体   繁体   English

C文件读取,空白/空行

[英]C File Reading , Blank/Empty Line

Helo, 喂,

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

input is the array of chars :) 输入是字符数组:)

This is the line of code ive got checking for a blank line in a file, but it never picks up a blank line for example.. 这是代码行检查文件中的空白行,但例如从不选择空白行。

My code reads in 8 digit hex values and i want to termiated when its invalid(already sorted) or when theres a empty line,line with white space or EOF. 我的代码读取8位十六进制值,我想在其无效(已排序)或空白行,空白行或EOF行时终止。

It works if my file is like this... 11111111 11111111 如果我的文件是这样,它就可以工作... 11111111 11111111

^with a space on the empty line but if theres no space it just breaks in to a infitie loop this is very annoying. ^在空行上有一个空格,但是如果没有空格,它只会闯入一个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);  
}

You need to check the return value of fgets . 您需要检查fgets的返回值。 This function returns NULL to signal "end of file". 此函数返回NULL以指示“文件结束”。 Simply put, try this: 简而言之,请尝试以下操作:

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

You can use this code to check if the line is empty or not : 您可以使用此代码检查行是否为空:

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

and test like this : 并像这样测试:

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

You use the wrong approach. 您使用了错误的方法。 You have to check whether the line ends with '\\n' and whether all characters before that character in the line are not printable. 您必须检查该行是否以'\\ n'结尾,以及该行中该字符之前的所有字符是否不可打印。 It is not enough to check just the first character. 仅检查第一个字符是不够的。

It should be something like that: 应该是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM