您的位置:首页 > 编程语言

UNIX环境高级编程程序1-2将标准输入复制到标准输出

2015-01-28 21:17 423 查看
//mycat/mycat.c
__
#include"apue.h"

#defineBUFFSIZE4096

intmain()
{
intn;
charbuf[BUFFSIZE];

//Byconvention,allshellsopenthreedescriptorswheneveranewprogramisrun:
//standardinput,standardoutput,andstandarderror.
//STDIN_FILENOspecifythefiledescriptorforstandardinput
//UnbufferedI/Oisprovidedbythefunctionsopen,read,write,lseek,andclose.
//Thesefunctionsallworkwithfiledescriptors.
//Thereadfunctionreturnsthenumberofbytesthatareread,andthisvalueisused
//asthenumberofbytestowrite.Whentheendoftheinputfileisencountered,read
//returns0andtheprogramstops.Ifareaderroroccurs,readreturns-1.
while((n=read(STDIN_FILENO,buf,BUFFSIZE))>0)
{
if(write(STDOUT_FILENO,buf,n)!=n)
{
err_sys("writeerror");
}
}

//usuallynisbiggerthan0,ifinputctrl+d
//thennisequalto0
if(n<0)
{
err_sys("readerror");
}

return0;
}
//ThestandardI/OfunctionsprovideabufferedinterfacetotheunbufferedI/O
//functions.UsingstandardI/Orelievesusfromhavingtochooseoptimalbuffersizes,
//suchastheBUFFSIZEconstantinFigure1.4.ThestandardI/Ofunctionsalsosimplify
//dealingwithlinesofinput(acommonoccurrenceinUNIXapplications).Thefgets
//function,forexample,readsanentireline.Thereadfunction,incontrast,readsa
//specifiednumberofbytes.AsweshallseeinSection5.4,thestandardI/Olibrary
//providesfunctionsthatletuscontrolthestyleofbufferingusedbythelibrary.
//ThemostcommonstandardI/Ofunctionisprintf.Inprogramsthatcall
//printf,we隆炉llalwaysinclude<stdio.h>normallybyincludingapue.hasthis
//headercontainsthefunctionprototypesforallthestandardI/Ofunctions.


makefile

mycat:mycat.c
g++-g-Wallmycat.c../lib/libapue.a-I../include-omycat
clean:
rmmycat














































内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: