简体   繁体   中英

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.

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.");

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

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.

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.
  2. you compare the pointer returned by fgets to 42 which is nonsense, BTW your compiler warned you.
  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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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