确定是否在控制台上打印了一些内容

时间:2019-04-29 00:57:18

标签: c

我试图确定控制台上是否打印了某些内容,这是正确的方法吗?或者,如果有更好的方法,请赐教。谢谢。

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

void main()
{
    char str[60];
    fgets(str,60,stdout);
    if (str == EOF)
    printf("theres nothing on the console");
    else printf("theres something printed on the console");
}

我确实修改了这段代码。却没有任何输出

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

int main()
{
    FILE *fp;
    fp = freopen("file.txt","w+", stdout);
    printf("hello");
    fclose(fp);
    fp = fopen("file.txt","r");
    if(feof(fp))
    printf("theres nothing on the console");
    else printf("theres something printed on the console");
    fclose(fp);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

stdout是用于输出的流。您不应尝试将其与fgets一起使用。与fgets配合使用将不会报告控制台上的内容。 fgetsstdout的返回值可能是空指针,表示错误。

标准C仅在stdin中提供输入流,在stdout中提供输出流,并在stderr中提供用于错误消息的输出流。这些流只是字符序列。除了按顺序打印简单消息外,C没有提供使用它们来检查或操作控制台或终端窗口的条件。

要与控制台或终端窗口进行交互,您需要标准C以外的软件,例如用于类Unix系统的 curses 软件。

此外,void main()不是main的标准声明。对于便携式用途,应为int main(void)int main(int argc, char *argv[])

if (str == EOF)是不正确的语句,因为strchar的数组,但是EOF实际上是int的值(它是一个扩展为整数常量表达式)。在str == EOF中使用时,str将从数组转换为指针。比较指向int的指针是不合适的。

相关问题