gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:39:52 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com