cat 命令用于连接文件并打印到标准输出设备上。
现在我们用C语言编程实现cat命令的作用,代码如下:
mycat.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc,char *argv[])
{
if(argc <= 1)
{
printf("no file to operate\n");
return 0;
}
int fd = open(argv[1],O_RDONLY);
if(fd < 0)
{
perror("open ");
return 0;
}
char str[20];
int count;
while((count = read(fd,str,20)) > 0)
{
write(1,str,count);
}
close(fd);
return 0;
}
代码文件编译运行如下,即可把hello.c打印出来
gcc mycat.c -o mycat
./mycat hello.c