텍스트A Linux file is a sequence of m bytes.
Regular file: contains arbitrary data
Directory: index for a related group of files
Socket: for communicating with a process on another machine
Opening files
int fd; //file descriptor
if ((fd = open("/etc/hosts", O_RDONLY)) < 0){
perror("open");
exit(1);
}
Closing files
int fd; //file descriptor
int retval; //return value
if ((retval = close(fd)) < 0){
perror("close");
exit(1);
}
Reading files
char buf[512];
int fd; //file descriptor
int nbytes; //number of bytes read
/* Open file fd ... */
/* Then read up to 512 bytes from file fd */
if ((nbytes = read(fd, buf, sizeof(buf))) < 0){
perror("read");
exit(1);
}
Writing Files
char buf[512];
int fd; //file descriptor
int nbytes; //number of bytes read
if ((fd = open("hello.txt", O_WRONLY|O_CREAT)) < 0){
...
}
/* Then write up to 512 bytes from buf to file fd */
if ((nbytes = write(fd, buf, sizeof(buf)) < 0){
perror("write");
exit(1);
}
File Offset
An offset of an opened file can be set explicitly by calling lseek(), lseek64()
off_t lseek(int fd, off_t offset, int whence);
offset: 기준 위치로부터 상대적인 변위를 나타냄
whence: 기준 위치
SEEK_SET: file의 맨 처음
SEEK_CUR: 현재 위치
SEEL_END: file의 맨 끝
char buf[512];
int fd; //file descriptor
off_t pos; //file offset
/* Get current file offset */
pos = lseek(fd, 0, SEEK_CUR);
/* The file offset is incremented by written bytes */
write(fd, buf, sizeof(buf));
/* Set file position to the first byte of the file */
pos = lseek(fd, 0, SEEK_SET);
Change peterpan.txt to uppercase letters
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char **argv)
{
int fd1, fd2; /* file descriptor */
int retval1, retval2; /* return value */
char buf; /* buffer */
int nbytes; /* number of bytes read */
if ((fd1 = open("peterpan.txt", O_RDONLY)) < 0){
perror("open");
exit(1);
}
if ((fd2 = open("peterpan_upper.txt", O_CREAT|O_WRONLY, 0666)) < 0){
perror("open");
exit(1);
} //files open
while(read(fd1, &buf, 1) != 0){
if (buf >= 97 && buf <= 122){
buf = buf - 32;
write(fd2, &buf, 1);
}
else
write(fd2, &buf, 1);
} //fd1 read, and then write to fd2
if((retval1 = close(fd1)) < 0){
perror("close");
exit(1);
}
if((retval2 = close(fd2)) < 0){
perror("close");
exit(1);
} //files close
}
-> file descriptor 두 개 생성
peterpan.txt를 read 모드로, peterpan_upper.txt를 write 모드로
-> buffer를 char type으로 선언하여 while문 안에서 한 글자씩 복사하고, 1)ASCII 번호가 소문자라면 대문자로 바꿔서 peterpan_upper.txt에 입력, 2)otherwise 복사한 그대로 peterpan_upper.txt에 입력