我实际上有一个解决这个问题的方法,但我想知道是否有一个更光滑的问题.
我需要在库中加载我的实用程序dlopen,然后调用其中一个函数.
不幸的是,该函数将大量信息喷出到STDOUT上,这是我不想要的.
我有一个不可移植的解决方案,我想知道是否有一个更好,更通用的解决方案,我可以使用.
这就是我所拥有的(注意:这是C):
/*
* Structure for retaining information about a stream, sufficient to
* recreate that stream later on
*/
struct stream_info {
int fd;
fpos_t pos;
};
#define STDOUT_INFO 0
#define STDERR_INFO 1
struct stream_info s_info[2];
point_stream_to_null(stdout, &s_info[STDOUT_INFO]);
point_stream_to_null(stderr, &s_info[STDERR_INFO]);
void *output = noisy_function();
reset_stream(stderr, &s_info[STDERR_INFO]);
reset_stream(stdout, &s_info[STDOUT_INFO]);
/*
* Redirects a stream to null and retains sufficient information to restore the stream to its original location
*** NB ***
* Not Portable
*/
void point_stream_to_null(FILE *stream, struct stream_info *info) {
fflush(stream);
fgetpos(stream, &(info->pos));
info->fd = dup(fileno(stream));
freopen("/dev/null", "w", stream);
}
/*
* Resets a stream to its original location using the info provided
*/
void reset_stream(FILE *stream, struct stream_info *info) {
fflush(stream);
dup2(info->fd, fileno(stream));
close(info->fd);
clearerr(stream);
fsetpos(stream, &(info->pos));
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
我有一个建议,它可以让您使用预处理器来实现可移植性,或者也许是“可移植性”。
如果你尝试类似的事情
#if defined __unix__
#define DEVNULL "/dev/null"
#elif defined _WIN32
#define DEVNULL "nul"
#endif
Run Code Online (Sandbox Code Playgroud)
(忽略其他操作系统,else case,错误指令等)然后像以前一样重新打开文件
FILE *myfile = freopen(DEVNULL, "w", stream);
Run Code Online (Sandbox Code Playgroud)
那么这可能会给你你想要的。
不过我还没有在家里尝试过这个。“nul”文件存在;请参阅Windows 中的 /dev/null。您可以在“预定义的 C/C++ 编译器宏”中获取预定义的宏。