-
fseek와 lseek 사용 정리 +ftellC_C++ 프로그래밍 2019. 6. 6. 20:10
fseek와 lseek
두 함수 모두 파일 포인터에 관련된 함수이다.
이 참에 매번 찾기 귀찮아서 정리를 해본다.
fseek?
1int fseek(FILE * stream, long offset, int whence)cs FILE의 포인터를 첫 번째 arg로 넣어준다.
1pFile = fopen("Text.txt", "w+");cs 다음과 같이하면 손 쉽게 사용이 가능하다.offset : 현재 위치에서 이동할 크기whence : 정의된 값이나 상수로 사용이 가능하다.SEEK_SET : 파일 시작
SEEK_CUR : 현재 파일 포인터 위치
SEEK_END : 파일의 끝123456789101112131415161718192021222324252627282930313233343536#include<stdio.h>#include<stdlib.h>#define print(n) printf("%ld\n",n);int main(int argc, char **argv){FILE *pFile = NULL;pFile = fopen("Text.txt", "w+");if(pFile == NULL){exit(0);}else{print(ftell(pFile));fputs("1234567890", pFile);print(ftell(pFile));fseek(pFile, 0L, SEEK_SET);print(ftell(pFile));fseek(pFile, 6L, SEEK_SET);print(ftell(pFile));fseek(pFile, -2L, SEEK_CUR);print(ftell(pFile));fseek(pFile, 0L, SEEK_END);print(ftell(pFile));fclose(pFile);}return 0;}cs lseek?
1int lseek(int fildes, off_t offset, int whence);cs filedes = 파일 디스크립터를 가진다.1fd = open("Text.txt", O_CREAT|O_RDWR);cs offset = 현재 위치에서 이동할 크기이다.whence : 정의된 값이나 상수로 사용이 가능하다.
SEEK_SET : 파일 시작
SEEK_CUR : 현재 파일 포인터 위치
SEEK_END : 파일의 끝12345678910111213141516171819202122232425262728293031323334353637383940414243444546#include<stdio.h>#include<stdlib.h>#include<fcntl.h>#include<unistd.h>#define print(n) printf("%d\n", n);int main(int argc, char ** argv){int fd; // File descriptorint position;fd = open("Text.txt", O_CREAT|O_RDWR);if(fd == -1){exit(0);}else{position = lseek(fd, 0, SEEK_CUR);print(position);write(fd, "1234567890", 11);position = lseek(fd, 0, SEEK_CUR);print(position);lseek(fd, 0L, SEEK_SET);position = lseek(fd, 0, SEEK_CUR);print(position);lseek(fd, 6L, SEEK_SET);position = lseek(fd, 0, SEEK_CUR);print(position);lseek(fd, -2L, SEEK_CUR);position = lseek(fd, 0, SEEK_CUR);print(position);lseek(fd, 0L, SEEK_END);position = lseek(fd, 0, SEEK_CUR);print(position);close(fd);}return 0;}cs ftell?
1long ftell(FILE * fp)cs 현재 파일 포인터가 가리키고 있는 위치를 반환한다.
에러 : -1
마무리
fseek는 파일 포인터를 사용하며
lseek는 파일 디스크립터를 사용한다.
ftell은 파일이 가리키고 있는 위치를 반환한다.
※ 본 글은 개인 포트폴리오 혹은 공부용으로 사용하기 때문에, 무단 복사 유포는 금지하지만, 개인 공부 용도로는 얼마든지 사용하셔도 좋습니다
반응형'C_C++ 프로그래밍' 카테고리의 다른 글
매우 큰 텍스트 파일 만들기 (0) 2019.06.19 epoll 함수와 구조체에 대해서 알아보자 (0) 2019.06.08 sscanf와 sprintf에 대해서 알아보자 (0) 2019.06.04 pthread_mutex_init (뮤텍스 사용하기!) (0) 2019.05.25