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 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 <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还是挺好玩,哈哈