系统编程人员要学会使用管道编程

在看洛杉矶大学的cs635课程课件时,有一个很简单的程序,模仿linux中的cat命令的,

链接为:http://cs.usfca.edu/~cruse/cs635/

该程序内容为:

//-------------------------------------------------------------------
//	mycat.c
//
//	This program shows how the default behavior of the standard
//	UNIX/Linux 'cat' command could readily be implemented in C.  
//	(Consult the 'man' page for 'cat' to see the 'options' that 
//	would need to be added to achieve a total 'cat' emulation.)
//
//		compile using:  $ gcc mycat.c -o mycat
//		execute using:  $ ./mycat <filename>
//
//	programmer: ALLAN CRUSE
//	written on: 24 AUG 2007
//-------------------------------------------------------------------

#include <fcntl.h>	// for open() 
#include <stdio.h>	// for perror() 
#include <unistd.h>	// for read(), write(), close() 

int main( int argc, char *argv[] )
{
	int	i, fd, ch;	// declare local variables

	for (i = 1; i < argc; i++)
		{
		fd = open( argv[i], O_RDONLY );
		if ( fd < 0 ) { perror( argv[i] ); continue; }
		while ( read( fd, &ch, 1 ) == 1 ) 
			write( STDOUT_FILENO, &ch, 1 );
		close( fd );
		}
}

其中在输出read得到的内容到标准输出时,使用的是write(STDOUT_FILENO, &ch, 1), 还可以将输出重定向到某个文件中。

我想起在编写pcie数据传输程序时,我还煞有介事的把得到到十进制整型转换成字符型然后存到文件里,这里看来只需要输出到STDOUT,然后重定向到文件,即可以达到目的。这就是菜鸟不懂基本系统编程的悲剧,花太多时间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值