在看洛杉矶大学的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,然后重定向到文件,即可以达到目的。这就是菜鸟不懂基本系统编程的悲剧,花太多时间