#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#define BUFF_SIZE 4096
int open_files(int count, char **names, int* fd)
{
int res = count, i;
for (i = 0; i < count; i++)
{
if ((fd[i] = open(names[i], O_RDONLY)) == -1 ||
(fd[i] != -1 && lseek(fd[i], 0, SEEK_END) == -1))
{
fd[i] = -1;
perror(names[i]);
res --;
}
}
return res;
}
void check_loop(int *fd, int file_count, char **fnames)
{
static char buffer[BUFF_SIZE];
int i, j;
while(1)
{
for (i = 0; i < file_count; i++)
{
if (fd[i] != -1)
{
int filesize = lseek(fd[i], 0, SEEK_END);
if (filesize > (1024 << 6))
{
lseek(fd[i], -BUFF_SIZE, SEEK_END);
int read_bytes = read(fd[i], buffer, BUFF_SIZE);
int pos[2], ind = 0;
for (j = read_bytes - 1; j >= 0 && ind < 2; j--)
{
if (buffer[j] == '\n')
{
pos[ind++] = j;
}
}
int tmpfd = open(fnames[i], O_TRUNC | O_WRONLY);
write(tmpfd, &buffer[pos[1] + 1], pos[0] - pos[1]);
close(tmpfd);
}
}
}
sleep(5);
}
}
int main(int argc, char *argv[])
{
int i;
int fd[argc];
if (open_files(argc - 1, argv + 1, fd))
{
check_loop(fd, argc - 1, argv + 1);
}
return 0;
}