Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdlib.h>
- int read_stdin();
- void reverse_string(char* str);
- int main(int argc, char **argv) {
- for(int i = 1; i < argc; i++) {
- char *filename = argv[i];
- int open_file = open(filename,O_RDONLY);
- char symbol;
- int lines = 0;
- if(open_file < 0) {
- char first = strlen("tail: cannot open '");
- char second = strlen("' for reading");
- char* err = malloc(first + strlen(filename) + second);
- strcat(err, "tail: cannot open '");
- strcat(err, filename);
- strcat(err, "' for reading");
- perror(err);
- free(err);
- continue;
- }
- /*if(argc > 2) {
- write(1, "==> ", 4);
- write(1, argv[i], strlen(argv[i]));
- write(1, " <==\n", 5);
- }*/
- //char ch;
- int read_file = read(open_file, &symbol, 1);
- if(read_file < 0) {
- char first = strlen("tail: error reading '");
- char second = strlen("'");
- char* err = malloc(first + strlen(filename) + second);
- strcat(err, "tail: error reading '");
- strcat(err, filename);
- strcat(err, "'");
- perror(err);
- free(err);
- continue;
- //return 3;
- }
- /*int write_file = write(STDOUT_FILENO, &symbol, 1);
- if(write_file < 0) {
- perror("tail: error writing");
- return 5;
- }*/
- if(argc > 2) {
- write(1, "==> ", 4);
- write(1, argv[i], strlen(argv[i]));
- write(1, " <==\n", 5);
- }
- off_t size = lseek(open_file,0,SEEK_END);
- ssize_t rb;
- for(int r = -2; lines < 10; r-- ) {
- size = lseek(open_file, r, SEEK_END);
- ssize_t already_read = read(open_file, &symbol ,1);
- if(symbol == '\n') lines++;
- }
- lines = 0;
- do{
- rb = read(open_file, &symbol, 1);
- ssize_t wb = write(STDOUT_FILENO,&symbol,1);
- if(symbol == '\n') lines++;
- if(wb < 0) {
- char *first = "tail: error writing 'standard output'";
- perror(first);
- break;
- }
- }while(rb > 0 && lines < 10);
- if(i != argc - 1) write(STDOUT_FILENO, "\n", 1);
- int close_file = close(open_file);
- if(close_file < 0) {
- char first = strlen("tail: error reading '");
- char second = strlen("'");
- char* err = malloc(first + strlen(filename) + second);
- strcat(err, "tail: error reading '");
- strcat(err, filename);
- strcat(err, "'");
- perror(err);
- free(err);
- }
- }
- //}
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement