상세 컨텐츠

본문 제목

UNIX system call - lseek

Computer Science/UNIX

by 2021. 9. 19. 20:01

본문

반응형

lseek(2)

#include <unistd.h>
/* the character l in the name lseek means “long integer” */
off_t lseek(int filedes, off_t offset, int start_flag);
// off_t 도 system primitive 헤더에 포함된 int / long 등의 자료형일 것임
// Returns : new file offset if OK, -1 on error

lseek은 일반적인 파일 즉 disk regular 파일에서만 사용가능하며 file offset을 마음대로 변경할 수 있다. 

lseek는 start_flag 설정에 따라 offset만큼 움직인 이후 offset (file position)값을 반환한다. 

 

lseek의 start_flag는 시작 위치에 대한 설정이며 다음과 같은 값들이 있다.

SEEK_SET  #0  : 시작 위치에서 offset만큼 이동
SEEK_CUR  #1  : 현재 file position에서 offset만큼 이동
SEEK_END  #2  : EOF위치에서 offest만큼 이동

SEEK_SET으로는 시작 위치 이전 position으로 이동할 수 없지만, SEEK_END로는 EOF 이후로 이동 가능하다.

 

example

off_t nepos;

newpos = lseek(fd, (off_t)-16, SEEK_END);
// EOF에서 앞으로 off_t만큼 이동
----------------------------------------------------------------------------

// 방법 1
fd = open(fname, O_RDWR);
lseek(fd, (off_t)0, SEEK_END); // EOF로 offset을 이동시키고 
write(fd, outbuf, OBSIZE); // EOF 뒤로 write

// 방법 2
fd = open(fname, O_WRONLY|O_APPEND); // APPEND 옵션은 EOF 뒤로 데이터추가이므로 같음
write(fd, outbuf, OBSIZE);

----------------------------------------------------------------------------

off_t filesize;
int filedes;

filesize = lseek(fd, (off_t)0, SEEK_END); /* filesize is the size of file */

 

반응형

'Computer Science > UNIX' 카테고리의 다른 글

UNIX - basic command summary(기본 명령어 정리)  (0) 2021.09.28
UNIX - File Share  (0) 2021.09.20
UNIX system call - write  (0) 2021.09.18
UNIX system call - close, read  (0) 2021.09.17
UNIX system call - create  (0) 2021.09.16

관련글 더보기