파일 읽기와 쓰기
파일의 내용을 읽기 위해 read 함수를 사용하며 write 함수를 사용함으로써 파일에 내용을 쓸 수 있다.
read와 write 함수의 리턴값의 데이터형은 ssize_t이며
ssize_t는 <sys/types.h>에 int(환경에 따라 long으로 정의되어 있다.
아마도 어떤 system은 int로, 어떤 system은 long으로 사용할 수도 있으니 데이터형을 따로 재정의한 듯 싶다.
파일 읽기: read
#include <unistd.h>
ssize_t read(int fildes, void *buf, size_t nbytes);
- fildes: file descriptor
- buf: 바이트를 저장할 memory 영역의 시작 주소
- nbytes: 읽어올 바이트 수
- file descriptor가 가리키는 파일에서 nbytes로 지정한 크기만큼 바이트를 읽고 buf로 지정한 memory 영역에 저장한다.
- read 함수는 실제 읽어온 바이트 수를 리턴하며, 오류가 발생하면 -1을 리턴한다.
- 만일 리턴값이 0이면 파일의 끝에 도달해 더 읽을 내용이 없음을 의미한다.
- 파일을 처음 열었을 때는 읽어올 위치를 나타내는 offset이 파일의 시작점을 가리키고 있는데, read 함수를 실행할 때마다 읽어온 크기만큼 이 offset이 이동하여 다음 읽어올 위치를 가리키게 된다.
- read 함수는 파일에 저장된 데이터가 어떤 종류의 데이터인지 상관없이 무조건 byte 단위로 읽어온다. 그래서 그 데이터를 종류에 맞게 처리하는 작업이 필요할 수 있으며 그것은 프로그래머의 몫이다.
Example
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(void) {
int fd, n;
char buf[10];
fd = open("unix.txt", O_RDONLY);
if (fd == -1) {
perror("Open");
exit(1);
}
n = read(fd, buf, 6);
if (n == -1) {
perror("Read");
exit(1);
}
buf[n] = '\0';
printf("n=%d, buf=%s\n", n, buf);
close(fd);
return 0;
}
# gcc -o ex1 ex1.c
# cat unix.txt
Unix System Programming
# ./ex1
n=6, buf=Unix S
파일 쓰기: Write
#include <unistd.h>
ssize_t write(int fildes, const void *buf, size_t nbytes);
- fildes: file descriptor
- buf: 파일에 기록할 데이터를 저장한 memory 영역
- nbytes: buf의 크기(기록할 데이터의 크기)
- file descriptor는 write를수행할 파일을 가리킨다.
- buf는 파일에 기록할 데이터를 저장하고 있는 memory 영역을 가리킨다.
- buf가 가리키는 memory 영역에서 nbytes로 지정한 크기만큼 읽어 파일에 쓰기를 수행한다.
- read와 마찬가지로 실제 쓰기를 수행한 바이트 수를 리턴한다.
- 오류가 발생할 경우 -1을 리턴.
Example
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int rfd, wfd, n;
char buf[10];
rfd = open("unix.txt", O_RDONLY);
if(rfd == -1) {
perror("Open unix.txt");
exit(1);
}
wfd = open("unix.bak", O_CREAT | O_WRONLY | O_TRUNC, 0644);
if(wfd == -1) {
perror("Open unix.bak");
exit(1);
}
while ((n = read(rfd, buf, 6)) > 0)
if(write(wfd, buf, n) != n) perror("Write");
if(n == -1) perror("Read");
close(rfd);
close(wfd);
return 0;
}
# gcc -o ex2 ex2.c
# ls unix.bak
unix.bak: 해당 파일이나 디렉토리가 없음
# ./ex2
# cat unix.bak
Unix System Programming
728x90
반응형
'Unix' 카테고리의 다른 글
memcpy, strcpy 문자열 복사 차이&사용법 (0) | 2022.10.10 |
---|---|
저수준 파일 입출력 (open, close) (2) | 2022.09.20 |