栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

linux的cat命令实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

linux的cat命令实现

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

代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

//主函数
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失败: %sn", 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 7月   2 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 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

//主函数
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失败: %sn", 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还是挺好玩,哈哈

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003022.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号