C编程,如何防止puts写入console?

C programming, how to prevent puts from writing to console?

假设您有一个 C 程序,它在将控制权返回给 main() 之前调用函数 int foo(),然后 main() 使用 puts() 写入控制台.

有哪些方法可以防止 puts 写入控制台?

您获得的唯一 #includes 是 stdio 和 stdlib。您不能触摸 main() 中的任何代码,只能触摸 foo().

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

unsigned int foo()
{
    //Your code here

    return 0;
}

int main()
{

    foo();
    puts("If you are reading this you have failed");
    return 0;
}

redirect stdout to somewhere else (like a normal file or a character device like /dev/null) with freopen()。在那里查看示例

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

int main(void)
{
    puts("stdout is printed to console");
    if (freopen("redir.txt", "w", stdout) == NULL)
    {
       perror("freopen() failed");
       return EXIT_FAILURE;
    }
    puts("stdout is redirected to a file"); // this is written to redir.txt
    fclose(stdout);
}

根据您的具体情况进行调整应该很简单

//Your code here,输入exit(EXIT_SUCCESS);