1、本篇實作cat命令的兩個基本功能
cat FilePath1 FilePath2 ... : 將該檔案的內容輸出到終端上
cat : 將鍵盤輸入的內容輸出到終端上
2、思路分析:
以上兩個功能實際上是完成了兩個檔案的重定向,
cat FilePath1 FilePath2 ... :將FilePath1 FilePath2 ... 檔案中的內容重定向到了標準輸出中,也就是檔案拷貝的功能,即將FilePath1 FilePath2 ...的內容拷貝到了標準輸出中,
cat : 將標準輸入(鍵盤)的內容拷貝到了標準輸出中,
3、代碼 和 測驗
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFER_LEN (512)
//檔案復制,將src_fd檔案中的內容copy到dest_fd檔案中
void copy(int src_fd,int dest_fd)
{
if((src_fd < 0 )||(dest_fd < 0))
{
printf("fd error,src_fd:%d,dest_fd:%d\n",src_fd,dest_fd);
return ;
}
char buf[BUFFER_LEN] = {0};
ssize_t size = 0;
while((size = read(src_fd,buf,BUFFER_LEN)) > 0)
{
if(write(dest_fd,buf,size) <= 0)
{
printf("write error\n");
}
}
}
int main(int argc ,char **argv)
{
if((argc < 1)||(memcmp("cat",argv[0],strlen("cat")) < 0))
{
printf("usage: cat xxx xxx\n");
return -1;
}
int std_in = STDIN_FILENO; //標準輸入 0
int std_out = STDOUT_FILENO; //標準輸出 1
int i = 0;
for(i = 1;i < argc;i ++)
{
std_in = open(argv[i],O_RDONLY);
if(std_in < 0)
{
printf("%s open error\n",argv[i]);
continue;
}
//將打開檔案的內容copy到標準輸出中去
copy(std_in,std_out);
close(std_in);
}
//如果只輸入了 cat 命令,將標準輸入的內容copy到標準輸出中去
if(argc == 1)
copy(std_in,std_out);
return 0;
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/264177.html
標籤:其他
上一篇:1.3.0-alpha04 Fragment result api
下一篇:Android 中導航欄文字居中
