2013-10-30 37 views
0

我明白如何打開一個文件並將該文件的內容寫入另一個文件。我想知道如何使用底層系統調用open() write() read() close()打開文件以打開相同的文件並將其寫入標準輸出。這可能嗎?使用系統調用將文件的內容寫入標準輸出?

// OPEN OUTPUT FILE 
if((output_file = open(argv[3], O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR)) < 0) 
{ 
    progress("couldn't open output"); 
    perror(argv[3]); 
    exit(1); 
} 

// OPEN INPUT FILE 
if((input_file1 = open(argv[1], O_RDONLY)) < 0) // open file 1 
{ 
    progress("couldn't open file1"); 
    perror(argv[1]); 
    close(output_file); 
    exit(1); 
} 

// WRITE   
while((n = read(input_file1, buffer, sizeof(buffer))) > 0) 
{ 
    if((write(output_file, buffer, n)) < 0) 
    { 
     perror(argv[3]); 
     close(input_file1); 
     close(output_file); 
     exit(1); 
    } 
} 
+0

標準輸出是0或1的值。您可以嘗試寫入(0,...)或寫入(1,...)。我不記得哪個是stdout,哪個是stdin。 –

回答

2

標準輸出只是另一個文件,它已經打開(除非它已關閉)。其文件描述符是STDOUT_FILENO,或者改變天然­ fileno(stdout),通過包括在POSIX <stdio.h>獲得:

write(STDOUT_FILENO, buffer, n) 
+0

謝謝!你是最好的 – Chips

相關問題