
|
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
main(int argc, char *argv[])
{
int fd;
off_t filesize;
if ((fd = open(argv[1], O_RDONLY)) == -1) {
perror("open failed");
exit(1);
}
/* 읽기/쓰기 포인터가 파일의 끝을 가리키게 되고,
변경된 읽기/쓰기 포인터가 반환되는데 이는 파일의 크기가 된다. */
if ((filesize=lseek(fd, 0, SEEK_END)) == -1) {
perror("lseek failed");
exit(1);
}
printf("%s\'s size is %d\n", argv[1], filesize);
close(fd);
exit(0);
}
===============================
5555.txt 파일이 생성되었고
그파일의 용량은 34바이트이다 26개쓴상태에서 4만큼 널집어넣고 4바이트인 ABCD를 써버려서
--------------------------------
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
main(int argc, char *argv[])
{
int fd;
if ((fd = open(argv[1], O_WRONLY)) == -1) {
perror("open failed");
exit(1);
}
/* 읽기/쓰기 포인터가 파일의 끝으로 이동 */
if (lseek(fd, 0, SEEK_END) == -1) {
perror("lseek failed");
exit(1);
}
/* 쓰기를 하면 파일의 뒤에 연결 */
write(fd, " ABCD", 5);
close(fd);
exit(0);
}
파일에 임의로 접근하기
lseek 함수
기능
읽기/쓰기 포인터의 위치를 임의로 변경한다.
기본형
off_t lseek(int fildes, off_t offset, int whence);
fildes : 읽기/쓰기 포인터의 위치를 임의로 변경할 파일의 파일 식별자
offset : 이동할 바이트 수
whence : 시작 지점
반환값
성공 : 변경된 읽기/쓰기 포인터
실패 : -1
헤더 파일
<sys/types.h>
<unistd.h>
=============================
whence
SEEK_SET 파일의 시작
SEEK_CUR 현재 읽기/쓰기 포인터가 가리키는 부분
SEEK_END 파일의 끝
■ 파일 끝보다 뒤 위치 지정 가능 pos = lseek(fd, 30, SEEK_SET)
■ 파일에 임의로 접근하기 pos = lseek(fd, 0, SEEK_END)
fd = open("alphabet", O_WRONLY | O_APPEND)
sokoban's Blog is powered by Daum & Tattertools