2016-03-29 3 views
-1

私はこれに相当するWindowsプラットフォーム用のポインタが必要です。 これは私が* nixプラットフォームのために従ったものであり、それはそうfar.Theリンクが変数を宣言考慮し、より拡張性の代替としてhereCコード内のWindowsプラットフォームで一時的にstderrをnullにリダイレクトします。

+1

これは、Windowsのために類似しているはずが、あなたは、 ''の#include に持っていると_dup2'代わりdup2' 'の' dup'、 'の代わりに' _dup'使用する必要があります、など –

+1

ああ、 ''/dev/null ''の代わりに '' nul ''を開く必要があります。 –

答えて

1

を見つけることができます動作しているようだ(あなたがerror_streamそれを呼び出すことができます?)これで、 stderrに設定して、他の時には他のファイルに設定しています(Windows NTではfopen(NUL_DEVICE_FILENAME, "wb");など)。

このコードの素晴らしい点の1つは、各OSに合わせてNUL_DEVICE_FILENAME(または機能全体)を変更できることです。機能は、移植性が低下するインターフェイスになるの動作が簡単になります。例えば、使用法については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); 
} 

test.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 
関連する問題