Cの標準出力をリダイレクトし、標準出力をリセットします

StackOverflow https://stackoverflow.com/questions/6805600

  •  25-10-2019
  •  | 
  •  

質問

Cのリダイレクトを使用して入力を1つのファイルにリダイレクトし、標準出力を再び設定して画面に印刷します。誰かがこのコードの何が問題なのか教えてもらえますか?

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char** argv) {
    //create file "test" if it doesn't exist and open for writing setting permissions to 777
    int file = open("test", O_CREAT | O_WRONLY, 0777);
    //create another file handle for output
    int current_out = dup(1);

    printf("this will be printed to the screen\n");

    if(dup2(file, 1) < 0) {
        fprintf(stderr, "couldn't redirect output\n");
        return 1;
    }

    printf("this will be printed to the file\n");

    if(dup2(current_out, file) < 0) {
        fprintf(stderr, "couldn't reset output\n");
        return 1;
    }

    printf("and this will be printed to the screen again\n");

    return 0;
}
役に立ちましたか?

解決

あなたの2番目 dup2 通話が間違っています、置き換えます:

if (dup2(current_out, 1) < 0) {

他のヒント

それが機能する前に必ずしなければならないことの1つは、電話することです fflush(stdout); 切り替える前 stdout その下からファイル記述子。おそらく起こっているのは、C標準ライブラリが出力をバッファリングしていることです。使用して記述するデータ printf() そうではありません 実際に バッファーがいっぱいになるまで、基礎となるファイル記述子に送信されます(またはプログラムがから戻ります main).

このような通話を挿入します:

    fflush(stdout);
    if(dup2(file, 1) < 0) {

両方の呼び出しの前に dup2().

交換するだけです dup2(current_out, file)dup2(current_out, 1), 、そして物事はよりうまく機能するはずです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top