c - 如何比较重定向文本文件C中的行数

标签 c stderr

#include <stdio.h>
#include <stdlib.h>

#define BUFFERSIZE 10

int main(int argc, char *argv[])
{
    char address[BUFFERSIZE];

    //checking text file on stdin which does not work
    if (fgets(address, BUFFERSIZE, stdin) < 42)
    {
        fprintf(stderr, "The program needs at least 42 addresses for proper functionality.");
    }

    //while reads the redirected file line by line and print the content line by line
    while(fgets(address, BUFFERSIZE, stdin) != NULL)
    {
        printf("%s", address);
    }

    return 0;
}

嗨,这是我的代码。不起作用。问题是我有一个重定向的外部文件 adresy.txt进入标准输入,我需要检查文件是否具有所需的行数。

文件必须具有的最小行数是 42。如果有 42 或更多行,则程序可以继续,如果没有,则会抛出 fprintf(stderr, "The program needs at least 42 addresses for proper functionality.");

我试过这样if (fgets(address, BUFFERSIZE, stdin) < 42)但它仍然告诉我无法比较指针和整数 像这样:warning: comparison between pointer and integer

在代码扩展中,我将比较用户的参数与 adresy.txt 中的参数。因此我需要 argc*argv []但现在我需要解决这个问题。

有什么建议可以解决吗?感谢您的帮助。

最佳答案

您的代码中存在几个问题:

  1. #define BUFFERSIZE 10 与您的行一样奇怪,但至少有 42 长。
  2. 您将 fgets 返回的指针与 42 进行比较,这是无意义的,顺便说一句,您的编译器警告过您。
  3. 使用您的方法,您实际上只显示两行中的一行
<小时/>

您可能想要这个:

#define BUFFERSIZE 200  // maximum length of one line

int main(int argc, char *argv[])
{
    char address[BUFFERSIZE];

    while(fgets(address, BUFFERSIZE, stdin) != NULL)
    {
      // here the line has been read 

      if (strlen(address) < 42)
      {
          // if the length of the string read is < 42, inform user and stop

          fprintf(stderr, "The program needs at least 42 addresses for proper functionality.");
          exit(1);
      }

      // otherwise print line
      printf("%s", address);
    }

    return 0;
}

关于c - 如何比较重定向文本文件C中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46891394/

相关文章:

c - va_args 不接受 C 中的有符号整数

java - 在 unix 重定向之前在 log4j 中捕获 stderr 和 stdout

Exec() 之后的 PHP StdErr

bash - bash 脚本中 stderr 的临时重定向

c - 无法使用生成的 NDK 工具链构建 C 代码

c - 尝试用C做GUI

c - 在c中设置链表

c - 了解 GStreamer 管道

dos - 如何在出错时退出批处理程序?

c++ - 在 C++ 中写入 stderr 时调用函数?