|
发表于 2004-4-4 17:53:57
|
显示全部楼层
写了一个,错误处理都没加,可能会有问题
程序是把文件一次读进file,用lines指向最后几行,用n控制输出字符数
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <unistd.h>
- int
- main(int argc, char *argv[])
- {
- int l, n;
- char **lines;
- int fd;
- struct stat st;
- char *file;
- int i;
- if(argc != 4){
- fprintf(stderr, "Usage: %s <file> <count_line> <byte>\n", argv[0]);
- exit(-1);
- }
- l = atoi(argv[2]);
- n = atoi(argv[3]);
- if(l == 0 || n == 0){
- fprintf(stderr, "count_line or byte is zero\n");
- exit(-1);
- }
-
- if((fd = open(argv[1], O_RDONLY)) < 0){
- fprintf(stderr, "Cannot open %s\n", argv[1]);
- exit(-1);
- }
- fstat(fd, &st);
- file = (char *)malloc(st.st_size + 1);
- lines = (char **)malloc(l * sizeof(char *));
- read(fd, file, st.st_size);
- file[st.st_size] = '\0';
- if(file[st.st_size - 1] == '\n')
- file[st.st_size - 1] = '\0';
- for(i = l - 1; i >= 0; i--){
- if((lines[i] = strrchr(file, '\n')) == NULL){
- lines[i] = file;
- break;
- }
- *lines[i] = '\0';
- lines[i]++;
- }
- if(i == -1)
- i = 0;
- for(;i < l; i++){
- if(strlen(lines[i]) < n)
- puts(lines[i]);
- else{
- write(STDOUT_FILENO, lines[i], n);
- printf("\n");
- }
- }
- close(fd);
- free(file);
- free(lines);
- exit(0);
- }
复制代码 |
|