Java中無法捕獲C程序printf輸出的問題

在測試 ConsoleRunner 的過程中發現一個有意思的現象,一段很簡單的 C 程序:

 

#include <stdio.h>

#include <windows.h>

 

int main() {

    int i = 0;

    for (;;) {

        printf("%d/n", i++);

        Sleep(500);

    }

    return 0;

}

 

ConsoleRunner 竟然無法捕獲其輸出,如果把 Sleep 拿掉就行,或者如果改用 C++ cout 也行,很奇怪,懷疑是緩衝區的問題,上網查找,果然如此,見“ fflush(stdout) 的用途是什麼(http://bbs.chinaunix.net/viewthread.php?tid=693309)”,程序中加上一行後,問題消失:

 

#include <stdio.h>

#include <windows.h>

 

int main() {

    int i = 0;

    for (;;) {

        printf("%d/n", i++);

        fflush(stdout);

        Sleep(500);

    }

    return 0;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章