简体   繁体   English

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

[英]how to compare number of rows in redirected text file C

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

Hi, this is my code. 嗨,这是我的代码。 Does not work. 不起作用。 The problem is that I have a redirected external file adresy.txt into stdin and I need to check if the file has the required number of rows. 问题是我将外部文件adresy.txt重定向到了stdin,我需要检查文件是否具有所需的行数。

The minimum number of rows that a file must have is 42. If it has 42 or more rows the program can continue, if not, it throws out the fprintf(stderr, "The program needs at least 42 addresses for proper functionality."); 文件必须具有的最小行数是42。如果文件具有42行或更多行,则程序可以继续,否则行将抛出fprintf(stderr, "The program needs at least 42 addresses for proper functionality.");

I tried it this way if (fgets(address, BUFFERSIZE, stdin) < 42) but it still tells me that I can not compare pointer and integer like so: warning: comparison between pointer and integer 我这样尝试过if (fgets(address, BUFFERSIZE, stdin) < 42)但它仍然告诉我我不能像这样比较指针和整数: warning: comparison between pointer and integer

In the code extension I will compare the arguments from the user to what is in adresy.txt therefore I need argc and *argv [] but now i need to solve this. 在代码扩展中,我将把用户的参数与adresy.txt的参数进行比较,因此我需要argc*argv []但是现在我需要解决这个问题。

Any advice how to fix it? 有什么建议如何解决吗? Thanks for any help. 谢谢你的帮助。

There are several problems in your code: 您的代码中存在几个问题:

  1. #define BUFFERSIZE 10 is odd as your lines but be at least 42 long. #define BUFFERSIZE 10很奇怪,但长度至少为42。
  2. you compare the pointer returned by fgets to 42 which is nonsense, BTW your compiler warned you. 您将fgets返回的指针与无意义的42进行比较,顺便说一句,编译器警告您。
  3. With your method you actually display only one line out of two 使用您的方法,实际上只显示两行中的一行

You probably want this: 您可能想要这样:

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

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

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