my_cat实现
功能:
-b 空行不标行号
-n 空行标行号
现在版本不支持读入多个文件,可以类似 ./a.out -b test -n test,因为optind每次while后都不移动,所以不知道如何实现类似./a.out -b test1 test2,多个文件读入。
Code:
知识点:getopd, fopen, fgets函数特性
/*************************************************************************
> File Name: my_cat.c
> Author: evadai
> Mail: ***@126.com
> Created Time: Tue 27 Oct 2020 04:11:13 PM CST
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_SIZE 1024
int b_flag = 0;
int n_flag = 0;
void my_cat(const char *name){
FILE *fp;
//文件无法打开
if ((fp = fopen(name, "r")) == NULL){
perror("name");//文件名 + 上一个错误原因
exit(1);
}
//正常
int count = 0;
char buff[MAX_SIZE] = {0};
while((fgets(buff, MAX_SIZE, fp)) != NULL){
if (n_flag || (b_flag && buff[0] != '\n')){
printf("%d\t%s", ++count, buff);
}else if(b_flag && buff[0] == '\n'){
printf("\n");
}else{
//不需要行号
printf("%s", buff);
}
//printf("%s", buff);//不用加\n
}
return;
}
int main(int argc,char **argv){
char ch;
//getopt取参规则?返回-1?
while ((ch = getopt(argc, argv, "bn")) != -1){
//printf("%c\n", ch);//循环取出所有参数,只输出b or n
//状态分类
switch (ch){
case 'b': b_flag = 1; break;
case 'n': n_flag = 1; break;
default://接收到b,n以外参数,输出正确的文件名+参数提示
fprintf(stderr, "Usage : %s [-b|-n] file\n ", argv[0]);
exit(1);//return -1
}
my_cat(argv[optind]);
b_flag = 0;
n_flag = 0;
}
//printf("%d %d", argc, optind);
//my_cat(argv[optind]);
return 0;
}
my_ls实现
功能
Code
知识点:
linux目录操作(dirent, opendir, readdir, access)
窗口尺寸取出(iostl, winsize)
分列输出【复杂!】
这篇博客介绍了两个实用的Linux命令行工具的实现:my_cat和my_ls。my_cat功能是读取文件并按指定选项显示内容,支持-b(不显示行号)和-n(显示行号)选项。my_ls则涉及目录操作和窗口尺寸获取,同时能够进行复杂的分列输出。文章深入探讨了getopt函数用于参数解析,以及dirent、opendir、readdir和access等文件操作函数的使用。
1372

被折叠的 条评论
为什么被折叠?



