簡體   English   中英

C 標准輸出到文件使用 dup

[英]C stdout to file using dup

我正在開發一個程序,要求用戶輸入 s、f 或 0 作為用戶輸入。 S 將預定義的消息打印到系統,f 將該預定義的消息寫入用戶作為參數給出的文件。 0 終止程序。

我需要使程序只有一個寫入標准輸出的寫入語句。 我必須將打印在標准輸出中的預定義消息復制到帶有 dup2 的文件中。

現在這兩個進程必須通過輸入分開(f 寫入文件,而 s 寫入標准輸出)所以我不確定如何在 switch 語句中實現它。

當您輸入 f 時,它不應該將任何內容打印到標准輸出。

這是我的代碼:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/wait.h>

#define BUFFER_SIZE 128
#define PERMS 0666

int main(int argc, char *argv[])
{
    char outBuffer[BUFFER_SIZE] = "This is a message\n";
    int count;
    int fd;
    char input =0;
    int a;
    int c;
    int k[2];
    pipe(k);
    if(argc!=2){
        printf("Provide an valid file as an argument\n");
        exit(1);
    }

    if((fd = open(argv[1],O_CREAT|O_WRONLY|O_APPEND,PERMS)) == -1)
    {
        printf("Could not open file\n");
        exit(1);
    }


        printf("0 to terminate, s to write to stdout, f to write to file\n");
        do{
        scanf(" %c", &input);
        switch(input)
        {

            case 'f':
            if((c = fork()) == 0)
            {
                close(k[0]);
                dup2(fd,1);
                close(k[1]);
             }
             else
             {
                close(k[0]);
                close(k[1]);
                wait(0);
                wait(0);
              }
              break;
            case 's':
            write(1,outBuffer,strlen(outBuffer));
           break;

            default:
            printf("Invalid Choice\n");

         }
     }while(input != '0');

     close(fd);
     return 0;
}

f 現在只是在按下 s(打印 outBufer 消息)或觸發默認開關后將標准輸出定向到文件

我想要的 output:

f
f
s
This is a message
s
This is a message
f

文件包含:

This is a message
This is a message
This is a message

這是我對這個問題的看法; I removed fork() and pipe() both to compile natively on Windows ( gcc -g -std=c11 -Wall -c main.c && gcc main.o -o main.exe ) and because I don't think they are必需的。 當我使用 MSYS2 編譯/測試時,我必須顯式刷新標准輸出,否則直到退出才會顯示信息消息。

我重構了switch塊,以便我們可以使用breakcontinue控制主循環,我將其重寫為while(1)

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

#define BUFFER_SIZE 128
#define PERMS 0666

int main(int argc, char *argv[]) {
    char outBuffer[BUFFER_SIZE] = "This is a message\n";
    int fd, fd_f, fd_s;
    char input = 0;

    if(argc != 2){
        printf("Provide an valid file as an argument\n");
        exit(1);
    }
    if((fd_f = open(argv[1], O_CREAT|O_WRONLY|O_APPEND, PERMS)) == -1){
        printf("Could not open file\n");
        exit(1);
    }

    printf("0 to terminate, s to write to stdout, f to write to file\n");
    fflush(stdout); // messages are not printed on MSYS2 without explicitly flushing

    fd_s = dup(STDOUT_FILENO); // set fd_s to stdout with dup(1)
    fd = dup(STDOUT_FILENO);
    // if fd is not initialised, calling dup2 will close(0) [i.e. close(stdin)]!
    while(1) {
        scanf("%c", &input);
        fflush(stdin);

        if(input == '0') break;
        else if(input == 'f') dup2(fd_f, fd); // close(fd) and alias fd_f to fd
        else if(input == 's') dup2(fd_s, fd);
        else {
            printf("Invalid Choice\n");
            fflush(stdout);
            continue;
        }
        write(fd, outBuffer, strlen(outBuffer));
    }

    close(fd_f);
    close(fd);
    return 0;
}

Output:

標准輸出

>main.exe file.txt
0 to terminate, s to write to stdout, f to write to file
f
f
s
This is a message
s
This is a message
f
p
Invalid Choice
0

>
# ./main.exe file.txt
0 to terminate, s to write to stdout, f to write to file
f
f
s
This is a message
f
p
Invalid Choice
0


文件.txt

This is a message
This is a message
This is a message

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM