C語言:io重新導向

來源:互聯網
上載者:User

什麼是IO重新導向?

C語言裡調用fprintf的時候可以向指定的fp(FILE *fp)寫入資料,但是調用printf函數時確不需要指定任何FILE*,為什嗎?

啟動一個C程式時,調用環境自動建立3個FILE*(stdin,stdout,stderr),並關聯相應的裝置,而我們的scanf使用的就是stdin,printf使用的是stdout,但是這種關聯在程式啟動的時候是可以改變的,這就是IO重新導向

每個標準輸入輸出描述符都有自己的緩衝,向他們的緩衝塊裡寫入資料,程式就可以調用相應的函數讀取,例如getchar()可以從stdin的緩衝塊裡讀取一個字元

#include <stdio.h>
int main()
{
printf("hello,world\n");
return 0;
}

# gcc -o hello hello.c

# ./hello

hello,world

# ./hello > 1.txt

printf預設的行為是向螢幕上列印一行文本,但是命令把輸出重新導向,printf向指定的檔案裡寫入文本

 

#include <stdio.h>
int main()
{
char c;
while((c=getchar())!=EOF)
{
printf("%c",c);
}
return 0;
}

 

# gcc -o echo echo.c

# ./echo

getchar預設行為是從鍵盤讀取輸入,包括分行符號

直到使用者從鍵盤輸入EOF(LINUX/UNIX是CTRL+D)

 

# ./hello < ./echo

hello,world

重新導向echo標準輸入,以hello產生的輸出作為輸入,

當hello沒有更多東西可以輸出的時候,會發送EOF給echo

 

# ./hello < ./echo > 2.txt

echo從hello得到輸入,並把自己的輸出重定位到某個檔案裡

 

 


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.