簡體   English   中英

如何將程序輸出重定向到文本文件

[英]How to redirect program output to text file

我想將程序的輸出重定向到文件。 我怎樣才能做到這一點? 目前尚未創建文件,我只能將輸出打印到控制台。

    int fd[2];
    int processId;
    int output;
    char filename[] = "output.txt";

    if((output = open(filename, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR)) == -1){
        fprintf(stderr, "Unable to create/open file '%s'\n", filename);
        return 1;
    }

    if(pipe(fd) == -1){
        fprintf(stderr, "Error creating pipe\n");
        return 2;
    }

    if((processId = fork()) == -1){
        fprintf(stderr, "Error forking\n");
        return 3;
    }   

    if(processId == 0){
        int newFD = dup(STDOUT_FILENO);
        char newFileDescriptor[2];
        sprintf(newFileDescriptor, "%d", newFD);
        dup2(fd[1], output);
        close(fd[0]);
        execl("./pipetest", "pipetest", newFileDescriptor, NULL);
    }else{
        close(fd[1]);
        char c[10];
        int r = read(fd[0], c, sizeof(char) * 10);

        if(r > 0){
            fprintf(stderr, "PIPE INPUT = %s", c);
            fwrite(c, 1, sizeof(c), output);
        }
    }

一個好的開始是不要忽視編譯器警告:

test.c: In function ‘main’:
test.c:42:13: warning: passing argument 4 of ‘fwrite’ makes pointer from integer without a cast [enabled by default]
             fwrite(c, 1, sizeof(c), output);
             ^
In file included from test.c:1:0:
/usr/include/stdio.h:715:15: note: expected ‘struct FILE * __restrict__’ but argument is of type ‘int’
 extern size_t fwrite (const void *__restrict __ptr, size_t __size,
               ^

intFILE*不可互換。 如果使用open ,請使用write進行write 如果使用fopen ,請使用fwrite編寫。

此外,您永遠不會修改流程的標准輸出。 相反,您修改了output ,這沒有任何意義。 以下是對代碼進行更改所需的最小操作:

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

int main() {                                                                                                                                                                                                                                                                                                                                                                                                                             
    int fd[2];                                                                                                                                                                                                                                                                                                                                                                                                                           
    int processId;                                                                                                                                                                                                                                                                                                                                                                                                                       
    int output;                                                                                                                                                                                                                                                                                                                                                                                                                          
    char filename[] = "output.txt";                                                                                                                                                                                                                                                                                                                                                                                                      

    if((output = open(filename, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR)) == -1){                                                                                                                                                                                                                                                                                                                                                          
        fprintf(stderr, "Unable to create/open file '%s'\n", filename);                                                                                                                                                                                                                                                                                                                                                                  
        return 1;                                                                                                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                                                                                                    

    if(pipe(fd) == -1){                                                                                                                                                                                                                                                                                                                                                                                                                  
        fprintf(stderr, "Error creating pipe\n");                                                                                                                                                                                                                                                                                                                                                                                        
        return 2;                                                                                                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                                                                                                    

    if((processId = fork()) == -1){                                                                                                                                                                                                                                                                                                                                                                                                      
        fprintf(stderr, "Error forking\n");                                                                                                                                                                                                                                                                                                                                                                                              
        return 3;                                                                                                                                                                                                                                                                                                                                                                                                                        
    }                                                                                                                                                                                                                                                                                                                                                                                                                                    

    if(processId == 0){                                                                                                                                                                                                                                                                                                                                                                                                                  
        int newFD = dup(STDOUT_FILENO);                                                                                                                                                                                                                                                                                                                                                                                                  
        char newFileDescriptor[2];                                                                                                                                                                                                                                                                                                                                                                                                       
        sprintf(newFileDescriptor, "%d", newFD);                                                                                                                                                                                                                                                                                                                                                                                         
        dup2(fd[1], STDOUT_FILENO); // You want to modify STDOUT_FILENO                                                                                                                                                                                                                                                                                                                                                                  
        close(fd[0]);                                                                                                                                                                                                                                                                                                                                                                                                                    
        execl("/bin/echo", "echo", newFileDescriptor, NULL); // switched to echo                                                                                                                                                                                                                                                                                                                                                         
    }else{                                                                                                                                                                                                                                                                                                                                                                                                                               
        close(fd[1]);                                                                                                                                                                                                                                                                                                                                                                                                                    
        char c[10];                                                                                                                                                                                                                                                                                                                                                                                                                      
        int r = read(fd[0], c, sizeof(char) * 10);                                                                                                                                                                                                                                                                                                                                                                                       

        if(r > 0){                                                                                                                                                                                                                                                                                                                                                                                                                       
            fprintf(stderr, "PIPE INPUT = %s", c);                                                                                                                                                                                                                                                                                                                                                                                       
            write(output, c, r); // use write instead of fwrite                                                                                                                                                                                                                                                                                                                                                                          
        }                                                                                                                                                                                                                                                                                                                                                                                                                                
    }                                                                                                                                                                                                                                                                                                                                                                                                                                    
}                                                                                                                                                                                                                                                                                                                                                                                                                                        

這是運行它的結果:

$ gcc test.c -o test
$ ./test
PIPE INPUT = 6
$ cat output.txt 
6

最簡單的方法是在bash上執行以下操作:

./myprogram > output.txt

這會將所有輸出重定向到output.txt

您可以使用freopen ,這可能是最簡單的方法:

if (!freopen("out.txt", "w", stdout))
{
    // failed to open the file stream, handle the error
}

然后,您可以僅使用printf寫入該文件。 您可以使用stderr進行相同的操作,但這可能不是一個好主意-根據定義, stderr用於報告錯誤,據我所知,慣例是將其輸出到控制台。

這是簡單示例如何執行此操作:

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

int main(void) {
    int out = open("/tmp/output.txt", O_WRONLY | O_CREAT, 0644);
    if (out == -1) {
        perror("open:");
        return -1;
    }
    int r;
    r = close(1); /* this closes stdout */
    if (r != 0) {
        perror("close:");
        return -1;
    }
    r = dup2(out, 1); /* this duplicates your file descriptor to stdout */
    if (r == -1) {
        perror("dup2:");
        return -1;
    }
    printf("this should go to the output file\n");
    return 0;
}

暫無
暫無

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

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