gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:12:56 24 4
gpt4 key购买 nike

我需要 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/

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