linux的cat命令实现

24 篇文章 0 订阅

cat是linux一个输出文件内容的命令,比较有意思,练习c语言,用c实现一个cat命令效果。

代码

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>

//主函数
int main(int argc, char* argv[])
{
	//没传参数直接返回
	if(argc<2)
	{
		return 0;
	}
    int fd = -1;
    int wr = -1;
    //打开文件
    if ((fd = open(argv[1], O_RDONLY, 0666)) < 0)
    {
        printf("创建或打开文件%s失败: %s\n", argv[1], strerror(errno));
        return -1;
    }

    //读数据
    char buf[1024];
    memset(buf, 0, sizeof(buf));
    lseek(fd, 0, SEEK_SET);
	//循环读取数据
	while(wr = read(fd, buf, sizeof(buf))>0)
	{
		//输出
		printf("%s", buf);
		memset(buf, 0, sizeof(buf));
	}
	//关闭文件
    close(fd);
	printf("\n");
    return 0;
}

编译测试

[root@zlzlinux see]# vim see.c
[root@zlzlinux see]# 
[root@zlzlinux see]# 
[root@zlzlinux see]# ll
总用量 24
-rw-r--r-- 1 root root   817 72 18:47 see.c
[root@zlzlinux see]# vim see.c
[root@zlzlinux see]# 
[root@zlzlinux see]# 
[root@zlzlinux see]# gcc -o see see.c
[root@zlzlinux see]# ./see see.c
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>

//主函数
int main(int argc, char* argv[])
{
	//没传参数直接返回
	if(argc<2)
	{
		return 0;
	}
    int fd = -1;
    int wr = -1;
    //打开文件
    if ((fd = open(argv[1], O_RDONLY, 0666)) < 0)
    {
        printf("创建或打开文件%s失败: %s\n", argv[1], strerror(errno));
        return -1;
    }

    //读数据
    char buf[1024];
    memset(buf, 0, sizeof(buf));
    lseek(fd, 0, SEEK_SET);
	//循环读取数据
	while(wr = read(fd, buf, sizeof(buf))>0)
	{
		//输出
		printf("%s", buf);
		memset(buf, 0, sizeof(buf));
	}
	//关闭文件
    close(fd);
	printf("\n");
    return 0;
}
[root@zlzlinux see]# mv see /usr/bin
[root@zlzlinux see]# touch test.txt
[root@zlzlinux see]# vim test.txt
[root@zlzlinux see]# 
[root@zlzlinux see]# see test.txt
111
222
333
444

[root@zlzlinux see]# cat test.txt
111
222
333
444
[root@zlzlinux see]# 

这样就用vim编了一个cat效果的命令,see就是打印文本数据。vim和gcc还是挺好玩,哈哈

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小乌鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值