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 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
#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(const char* path, ssize_t* file_size, int* file_lines)
{
int i;
int fd_source;
int nb_line_file = 0;
char buffer[TAILLE];
ssize_t nb_octets_readed;
ssize_t nb_octets_readed_final = 0;
/* Open the file */
fd_source = open(path, O_RDONLY);
if (fd_source == -1)
{
perror("Erreur open:");
exit(EXIT_FAILURE);
}
/* 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;
close(fd_source);
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(const char* path, ssize_t* file_size, int* file_lines, int* readed_lines)
{
int fd_source;
int nb_lines = 0;
int i;
off_t pos;
char buffer[TAILLE];
ssize_t nb_octets_readed;
/* Recurisf / display */
if (*readed_lines <= N)
{
/* Open the file */
fd_source = open(path, O_RDONLY);
if (fd_source == -1)
{
perror("Error open :");
exit(EXIT_FAILURE);
}
/* Positionning the cursor */
pos = lseek(fd_source,-(*file_size-TAILLE), SEEK_END);
*file_size -= TAILLE; /* sbtract the size to re-set the cursor */
printf("new file size : %ld\n",*file_size);
if (pos == -1)
{
perror("Error lseek");
exit(EXIT_FAILURE);
}
/* Read */
nb_octets_readed = read(fd_source, buffer, TAILLE);
*readed_lines += get_buffer_lines(buffer);
mread(path,file_size,file_lines,readed_lines);
}
for (i=0; i<TAILLE; i++)
{
printf("%c",buffer[i]);
}
close(fd_source);
}
void tail_0 (const char *path, int ntail)
{
ssize_t file_size;
int file_lines;
int readed_lines = 0;
/* get file info (number of lines + size of file) */
get_file_info(path,&file_size,&file_lines);
printf("File : %s\nFile Size : %ld\nFile Lines : %d\n",path,file_size,file_lines);
/* All */
mread(path,&file_size,&file_lines,&readed_lines);
}
int main (int argc, char *argv[])
{
tail_0(argv[1],0);
return 0;
} |
Partager