如何在c中的文本文件中获取空行?

How to get an empty line in text file in c?

我有一个文件,其中包含一些关于异常的数据。每个字节的数据都写在文本文件的新行中。现在为了分隔不同异常的数据,我在每个数据集的最后一个字节之后添加了一个空行,即“\n”。我正在使用函数:

while ((read = getline(&line, &len, fp)) != -1)
{
     data[counter++] = (unsigned char)strtol(line,NULL,16);
     printf("The data received is %08x\n\r", data[counter - 1]);
} 

那么如何检测该行是否为空行?

继续我的评论,所有 line-oriented 输入函数(例如 fgets 和 POSIX getline)读到,并且在它们填充的缓冲区中包括 '\n',在您的情况下为 line。因此,要检查您是否遇到(或读取)了一个空行,您只需检查 line 的内容是否为 '\n'。要获得 line 中的第一个字符,您需要做的就是取消引用它,例如*line 并将第一个字符与 '\n' 字符进行比较,例如

while ((read = getline(&line, &len, fp)) != -1)
{
    if (*line == '\n') {
        /* handle empty line */
    }
    data[counter++] = (unsigned char)strtol(line,NULL,16);
    printf("The data received is %08x\n\r", data[counter - 1]);
}

注意*line 取消引用 lineline[0] 相同。您只是在检查第一个字符。这是由于指针相当于一个索引。例如指针表示法中的 line[x]*(line + x)。 (当 x=0 时,它只是 *line

另请注意,您应该通过包含 errno.h 并在每次转换后检查 errno 来验证 strtol 转换。您还应该将 strtol 的结果保存在 long 中以防止 under/overflow,然后将 tmp0UCHAR_MAX 进行比较(在 limits.h) 在分配给 data[counter++] 之前,例如

#include <errno.h>
#include <limits.h>
...

while ((read = getline(&line, &len, fp)) != -1)
{
    long tmp;
    if (*line == '\n') {
        /* handle empty line */
    }
    errno = 0;                      /* reset errno to 0 */
    tmp = strtol(line,NULL,16);     /* convert to a long */
    if (errno != 0) {
        /* handle error */
    }
    if (0 <= tmp && tmp <= UCHAR_MAX) {  /* check it will fit in unsigned char */
        data[counter++] = (unsigned char)tmp;
        printf("The data received is %08x\n\r", data[counter - 1]);
    }
    else
        /* handle error - tmp too large for unsigned char */
}

检查一下,如果您还有其他问题,请告诉我。