使用C语言简单模拟Linux的cat程序
来源:互联网 发布:淘宝网买家信用 编辑:程序博客网 时间:2024/05/19 00:49
先给出源码
//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 linuxlinuxokok^C[root@bogon mycode]# ./a.out test.txtokthat is finelinux[root@bogon mycode]# ./a.out test.txt fileio.c okthat is finelinux#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.txtError: No such file or directoryokthat is finelinux[root@bogon mycode]#
这个小程序免不了有bug,大神们发现了的话可以留言交流一下,谢谢
阅读全文
0 0
- 使用C语言简单模拟Linux的cat程序
- C语言模拟Linux中的cat程序
- malloc的简单使用-c语言程序
- 用C语言实现Linux命令的cat功能
- c笔记——linux cat命令的简单实现
- 【C语言】没事可以试试这个小程序,使用文件操作,模拟实现一个简单的文件拷贝工具!
- cat程序实现原理解释 C语言
- Linux命令cat/vi/more/head/tail的简单使用
- C语言实现linux中cat命令
- 简单的C语言程序
- 简单的c语言程序
- Linux下C语言程序简单的编写和调试
- 【C语言】linux下简单的聊天室程序(TCP+多线程)
- 模拟linux的 cat命令 读取文件
- C语言模拟简单的计算器
- linux下cat的使用
- linux cat命令的使用
- Linux cat命令的使用
- iOS 获取网络图片的尺寸
- RSI指标详解图解
- Android 7.0 行为变更
- 有一群海盗(不多于20人),在船上比拼酒量。(穷举)
- 第4节---模拟登陆知乎
- 使用C语言简单模拟Linux的cat程序
- 配置 七牛云cdn 加速
- J2EE系列之Hibernate4学习笔记(十六)--hibernate查询方式
- marquee标签
- JMeter接口测试
- JAVA 基本类型与 引用类型区别
- Docker(1)-- 如何安装Docker
- HelloKotlin(kotlin配置环境变量,kotlin hello world,kotlin 入门)
- groovy的集合 Range