二、head命令實現
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include "rio.h" #define MAXSIZE 4096 int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "usage %s [-n n] filename\n", argv[0]); return -1; } int times = 10, i = 0, in_fd = -1, n_char = 0; char filename[16] = {0}; char buf[MAXSIZE] = {0}; rio_t rio_buf = {0}; for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-n")) { times = atoi(argv[++i]); } else { snprintf(filename, sizeof(filename), "%s", argv[i]); } } if ((in_fd = open(filename, O_RDONLY)) == -1) { fprintf(stderr, "open %s failed\n", filename); return -1; } rio_readinitb(&rio_buf, in_fd); if ((n_char = rio_readlineb(&rio_buf, buf, MAXSIZE, times)) > 0) { write(STDOUT_FILENO, buf, n_char); } close(in_fd); return 0; } View Code三、tail命令實現
#include "rio.h" #define MAXSIZE 4096 void show_info(char *buf, char **ptr, int count); int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "usage %s [-n n] filename\n", argv[0]); return -1; } int times = 10, i = 0, in_fd = -1; char filename[16] = {0}; char buf[MAXSIZE] = {0}; rio_t rio_buf = {0}; char *ptr[MAXSIZE]; for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-n")) { times = atoi(argv[++i]); } else { snprintf(filename, sizeof(filename), "%s", argv[i]); } } if ((in_fd = open(filename, O_RDONLY)) == -1) { fprintf(stderr, "open %s failed\n", filename); return -1; } rio_readinitb(&rio_buf, in_fd); rio_read(&rio_buf, buf, MAXSIZE); show_info(buf, ptr, times); return 0; } void show_info(char *buf, char **ptr, int times) { int num = 0; int flag = 0; if (num < times) { *ptr = strrchr(buf, '\n'); flag = 1; **ptr = '\0'; show_info(buf, ptr + 1, --times); } if (flag) { printf("%s\n", *ptr + 1); } } View Code通過遞歸show_info來實現按順序打印,其實也可以用鏈表來實現,不過遞歸寫起來簡單。
http://xxxxxx/Linuxjc/1154885.html TechArticle