c - 在 Windows 平台上,C 代码中的临时重定向 stderr 为 null。

标签 c windows redirect stderr

我需要 Windows 平台上的等效项,请问有什么指示吗? 这是我在 *nix 平台上遵循的方法,到目前为止似乎有效。可以找到链接 here

最佳答案

作为一种更具扩展性的替代方案,请考虑声明一个变量(您可以将其称为 error_stream?),有时您将其设置为 stderr,有时您将其设置为 stderr。设置为其他文件(例如 Windows NT 上的 fopen(NUL_DEVICE_FILENAME, "wb");)。

此代码的一个好处是您可以更改NUL_DEVICE_FILENAME(甚至整个函数)以适合每个操作系统;这些函数成为一个接口(interface),使可移植性较差的行为更容易移植。请参阅 test.c(靠近本文底部)了解示例用法,以及下面的输出作为其工作原理的证明。祝你好运这个片段...:)

error_stream.h:

#ifndef INCLUDE_ERROR_STREAM
#define INCLUDE_ERROR_STREAM
#include <stdio.h>

FILE  *get_error_stream(void);
void   set_error_stream(FILE *);
void reset_error_stream(void);
void blank_error_stream(void);
#endif
<小时/>

error_stream.c:

#include "error_stream.h"
#define NUL_DEVICE_FILENAME "NUL" /* This worked fine for me on Win10 */
                                  /* Try "\\Device\\Null", "NUL" and  *
                                   *  ... "NUL:" if it doesn't work,  *
                                   *  ... or obviously "/dev/null" on *
                                   *  ... *nix                        */
FILE *error_stream, *blank_stream;
FILE *get_error_stream(void) {
    if (!error_stream) {
        error_stream = stderr;
    }
    return error_stream;
}
void set_error_stream(FILE *f) {
    error_stream = f;
}
void reset_error_stream(void) {
    set_error_stream(stderr);
}
void blank_error_stream(void) {
    if (!blank_stream) {
        blank_stream = fopen(NUL_DEVICE_FILENAME, "wb+");
    }
    set_error_stream(blank_stream);
}
<小时/>

测试.c:

#include "error_stream.h"
int main(void) {
    fputs("Testing\n", get_error_stream());
    blank_error_stream();

    fputs("Testing\n", get_error_stream());
    reset_error_stream();

    fputs("One\n", get_error_stream());
    blank_error_stream();

    fputs("Two\n", get_error_stream());
    reset_error_stream();
}
<小时/>
C:\Users\Seb\Desktop>gcc -c error_stream.c -o error_stream.o
C:\Users\Seb\Desktop>gcc test.c error_stream.o -o test.exe
C:\Users\Seb\Desktop>test
Testing
One

关于c - 在 Windows 平台上,C 代码中的临时重定向 stderr 为 null。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36283630/

相关文章:

windows - 无法为 "14/1033/styles/Themable/corev4.css"创建缓存安全 URL,找不到文件。请验证该文件是否存在于 layouts 目录下

windows - 我无法下载 mongoose.exe

javascript - 如果用户使用 Bootstrap 对话框确认,则重定向到相应的链接

c++ - 将 C++ 结构传递给需要 C 结构的库

c - 下面的宏有什么用?

c - 结构体数组中矩阵的动态内存分配

http - 我的浏览器如何将我的 http 请求转换为 https?

c - scanf仅交替工作

c++ - 如何 Hook AllocMem()、FreeMem() 等...调用?它可以是任何类型的技术 dll、可执行文件等

php - 通过 .htaccess 子域传递的 GET 参数未被 php 读取