1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/types.h>
#define TAILLE 16
static int N = 10;
void get_file_info(int fd_source, ssize_t* file_size, int* file_lines, int* fid)
{
int i;
int nb_line_file = 0;
char buffer[TAILLE];
ssize_t nb_octets_readed;
ssize_t nb_octets_readed_final = 0;
/* Read the file */
while ((nb_octets_readed = read(fd_source, buffer, TAILLE)) > 0)
{
/* Count number of return to the line */
for (i=0; i<nb_octets_readed; i++)
{
if ( buffer[i] == '\n')
nb_line_file++;
}
/* Size of the file */
nb_octets_readed_final += nb_octets_readed;
}
*file_size = nb_octets_readed_final;
*file_lines = nb_line_file;
return;
}
int get_buffer_lines(char buffer[])
{
int i;
int nb = 0;
for (i=0; i<TAILLE; i++)
{
if ( buffer[i] == '\n')
nb++;
}
return nb;
}
void mread(int fd_source, ssize_t file_size, int* readed_lines, int *actual_pos)
{
off_t pos;
char buffer[TAILLE];
ssize_t nb_octets_readed;
if (*readed_lines <= N)
{
/* Positioning the cursor */
pos = lseek(fd_source,*actual_pos-file_size, SEEK_END);
if (pos == -1)
{
perror("Error lseek");
exit(EXIT_FAILURE);
}
*actual_pos += TAILLE;
//printf("readed lines : %d | acutal_pos : %d\n",*readed_lines,*actual_pos);
/* Read */
nb_octets_readed = read(fd_source, buffer, TAILLE);
*readed_lines += get_buffer_lines(buffer);
write(STDOUT_FILENO, buffer, nb_octets_readed);
mread(fd_source,file_size,readed_lines,actual_pos);
}
else
{
return;
}
}
void tail_0 (const char *path, int ntail)
{
ssize_t file_size;
int file_lines;
int readed_lines = 0;
int actual_pos = 0;
int fd_source;
/* Open the file */
fd_source = open(path, O_RDONLY);
if (fd_source == -1)
{
perror("Erreur open:");
exit(EXIT_FAILURE);
}
/* get file info (number of lines + size of file + file_id) */
get_file_info(fd_source,&file_size,&file_lines,&fd_source);
printf("File : %s (%d) | File Size : %ld | File Lines : %d\n",path,fd_source,file_size,file_lines);
/* All */
mread(fd_source,file_size,&readed_lines,&actual_pos);
close(fd_source);
}
int main (int argc, char *argv[])
{
tail_0(argv[1],0);
return 0;
} |
Partager