使用C语言简单模拟Linux的cat程序

先给出源码

//fileio.c
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
void print(int fd)
{
    int i,len;
    char buf[10];
    len=read(fd,buf,10);//len是成功读入的字节数,每read一次,文件偏移量就会偏移10个字节位置
    while(len>0)//循环打印,直至读到文件尾部了
    {
        for(i=0;i<len;i++)
        {
            printf("%c",buf[i]);
        }
        len=read(fd,buf,10);
    }
}
void prin()
{
    char buf[1024];//我对指针还不熟,不过换成指针应该会好点吧
    while(1)//死循环打印字符串
    {
        scanf("%s",buf);
        puts(buf);
    }
}
int main(int argc,char *argv[])//argc参数个数,注意为1时代表没有参数(只有程序名字),argv[]是指参数,argv[1]指第一个参数,argv[2]指第二个参数。。。
{
    int fd,i;
    if(argc==1)//没有参数,跳到prin函数,
    {
        prin();
        return 0;
    }
    for(i=1;i<=argc-1;i++)//因为argc为2时才表示有一个参数啊
    {
        fd=open(argv[i],O_RDWR);//以可写可读方式打开
        if(fd==-1)//打开失败
        {
            perror("Error");//显示错误信息
        }   
        else
        {
            print(fd);//打开成功跳转print函数
        }
        close(fd);//记得打开之后关闭文件描述符
    }   
    return 0;
}

下面给演示一下我的运行结果

[root@bogon mycode]# gcc fileio.c 
[root@bogon mycode]# ./a.out 
linux
linux
ok
ok
^C
[root@bogon mycode]# ./a.out test.txt
ok
that is fine
linux
[root@bogon mycode]# ./a.out test.txt fileio.c 
ok
that is fine
linux
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
void print(int fd)
{
    int i,len;
    char buf[10];
    len=read(fd,buf,10);
    while(len>0)
    {
        for(i=0;i<len;i++)
        {
            printf("%c",buf[i]);
        }
        len=read(fd,buf,10);
    }
}
void prin()
{
    char buf[1024];
    while(1)
    {
        scanf("%s",buf);
        puts(buf);
    }
}
int main(int argc,char *argv[])
{
    int fd,i;
    if(argc==1)
    {
        prin();
        return 0;
    }
    for(i=1;i<=argc-1;i++)
    {
        fd=open(argv[i],O_RDWR);
        if(fd==-1)
        {
            perror("Error");
            //continue;
        }   
        else
        {
            print(fd);
        }
        close(fd);
    }   
    return 0;
}
[root@bogon mycode]# ./a.out nothisfile.txt test.txt
Error: No such file or directory
ok
that is fine
linux
[root@bogon mycode]#

这个小程序免不了有bug,大神们发现了的话可以留言交流一下,谢谢

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值