cat是将文本连接起来的程序,将第二个及以后的文件存到第一个里
#include <stdio.h>
#include <fcntl.h>
//将fdin复制到fdout里,接着上一次写
void filecopy(int fdin, int fdout)
{
char c;
while( read(fdin, &c, 1) == 1 )
write(fdout, &c, 1);
}
int main( int argc, char *argv[] )
{
int fdin, fdout;
if((fdin = open(*++argv, O_RDONLY, 0)) == -1)
{
write( 2, "ERROR :Can't open", 17);
write( 2, *argv, sizeof( *argv ));
}
if( argc == 1 )//标准输入到标准输出
filecopy( 0, 1 );
else
while( --argc )
{
if( (fdout = open(*++argv, O_WRONLY, 0)) == -1 )
{
write( 2, "ERROR :", 7);
write( 2, *argv, 20);
}
else
filecopy(fdin, fdout);
}
return 0;
}
题目来自《c程序设计语言》
另外书上第七章还有用文件操作实现的cat。