본문 바로가기

UNIX_LINUX_C_C++

tail.c 소스 (tail -f 기능 구현 open & fopen)

http://n1emand.blogspot.com/2012/01/tailc-tail-f-open-fopen.html

tail.c 소스 (tail -f 기능 구현 open & fopen)

/******************************************************************/
/* 함수명 : mytail
/* 기 능 : tail 명령 -f 옵션과 동일한 기능을 한다. 성능까지 동일한지는 장담못함 ^^
/* 작성자 : 김준남 Niemand
/* 작성일 : 2002-08-30 11:51오전
/* 수정일 : 2002-09-04 3:36오후 파일 앞에서, 파일포인터를 읽은부분만큼 뒤로 이동하던 것을
/* 파일 뒤에서, 파일포인터를 안 읽은부분만큼 앞으로 이동하는 것으로 변경.
/* 컴파일 : cc -o mytail mytail.c
/* 사용법 : mytail
/******************************************************************/
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAXBUFF 1024

int main(int arg, char *argv[])
{
int nfile = -1; // 파일포인터
int nRet = 0; // read() 결과값
off_t nUnRead = 0; // lseek() 의 이동위치값
char cBuff[1024]; // read buffer
ssize_t nRead = 0; // 읽은파일크기 저장
char cFileName[256]; // 파일명 변수
struct stat s; // 파일정보를 위한 시스템 변수

memset(cFileName, 0x00, 256);
strcpy(cFileName, argv[1]);

/**** 주석처리하면 파일 처음부터 출력하고 난 후 추가되는 내용을 출력 ****/
nfile = open(cFileName,O_RDONLY);
fstat(nfile, &s);
nRead = s.st_size;
close(nfile);
/**** 주석처리 안 하면 실행한 다음부터 추가되는 파일내용을 출력함 *******/

while(1)
{
usleep(100000); // 읽는 주기(이 방식이 좀 찜찜함)

nfile = open(cFileName,O_RDONLY);
fstat(nfile, &s);

nUnRead = s.st_size - nRead; // 안 읽은 부분 = 현재파일크기 - 아까 읽은 내용크기

lseek(nfile, (off_t) - nUnRead, SEEK_END); // 파일 뒤에서 nUnRead만큼 파일포인터 앞으로 이동한 후

while((nRet = read(nfile, cBuff, MAXBUFF)) > 0) // 그 위치서부터 읽기 시작
{
printf("%s", cBuff);
memset(cBuff, 0x00, 1024);
nRead = s.st_size; // 읽은 파일크기 저장.( 좀 찜찜)
}
close(nfile);
}
}


/******************************************************************/
/* 함수명 : myftail
/* 기 능 : tail 명령 -f 옵션과 동일한 기능을 한다. 성능까지 동일한지는 장담못함 ^^
/* 작성자 : 김준남 Niemand
/* 작성일 : 2002-08-30 11:51오전
/* 수정일 : 2002-09-04 3:36오후 파일 앞에서, 파일포인터를 읽은부분만큼 뒤로 이동하던 것을
/* 파일 뒤에서, 파일포인터를 안 읽은부분만큼 앞으로 이동하는 것으로 변경.
/* 컴파일 : cc -o myftail myftail.c
/* 사용법 : myftail
/******************************************************************/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MAXBUFF 4096

int main(int arg, char *argv[])
{
FILE * nfile; // 파일포인터
int nRet = 0; // read() 결과값
char cBuff[1024]; // read buffer
char cFileName[256]; // 파일명 변수
fpos_t posn;
int nFirst = 0;


memset(cFileName, 0x00, 256);
strcpy(cFileName, argv[1]);
//printf("fpos_t size = [%d]\n", sizeof(fpos_t));

nfile = fopen(cFileName,"r");
while(fgets(cBuff, MAXBUFF, nfile));
fgetpos(nfile, &posn);
fsetpos(nfile, &posn);
nFirst = 1;
fclose(nfile);

while(1)
{
usleep(1000); // 읽는 주기(이 방식이 좀 찜찜함)

nfile = fopen(cFileName,"r");
if(!nFirst)
{
fgetpos(nfile, &posn);
nFirst = 1;
}
fsetpos(nfile, &posn);
while(fgets(cBuff, MAXBUFF, nfile)) // 그 위치서부터 읽기 시작
{
printf("%s", cBuff);
memset(cBuff, 0x00, 1024);
}
fgetpos(nfile, &posn);
fclose(nfile);
}
}