반응형
Basic file system calls: open, read, write
1. open
open함수를 사용하면 "/aa/bb"라는 file을 read-write가 가능하도록 open 한다.open함수는 file descriptor라고 부르는 고유 번호를 return 한다.- file descriptor
0(standard input)1(standard output)2(standard error)
- 아래 예제에서
x는 file descriptor를 받는다. - file descriptor의 범위가 0부터 2까지이기 때문에
x는 3 미만일 것이다.
- file descriptor
x = open("/aa/bb", O_RDWR, 00777);
or
char fname[20];
strcpy(fname, "/aa/bb");
x = open(fname, O_RDWR, 00777); // fname contains "/aa/bb"
- The opening mode can be
O_RDONLY- open for read only
O_WRONLY- open for write only
O_RDWR- open for read and write
O_RDWR | O_CREAT | O_TRUNC- open for read and write.
- 존재하지 않으면, 생성한다.
- 새로운 내용을 작성하기 전에 미리 비운다. (empty)
- Permission mode
00777은 기본(default) permission mode를 의미한다.
- "/aa/bb"는 파일의 절대경로(absolute path)이다.
- 만약, 경로가
/로 시작하지 않는다면 그것은 상대경로(relative path)이다. - 상대경로는 현재 디렉토리에서 탐색을 시작한다.
- 만약, 경로가
x = open("d1/f1", O_RDWR, 00777);다음과 같은 순서로 파일을 찾을 것이다.- 현재 디렉토리에서
d1탐색 d1디렉토리에서f1탐색
- 현재 디렉토리에서
2. read
y = read(x, buf, 10);
- 위의
read함수는 파일x의 현재 file position에서 시작해서 최대10bytes를 읽어 character arraybuf에 저장한다. 10만큼 읽는다면, File position이10만큼 움직인다.- 파일이 처음 열렸을 때의 file position
0이다. - 시스템은
y에 실제로 읽은 바이트 수만큼 반환한다. - 만약, 파일을 읽는 도중, 에러가 발생한다면
-1을 반환한다. - File position이 파일의 끝까지 도달하면
0을 반환한다.
3. write
y = write(x, buf, 10);
- 위의
write함수는buf의 현재 file position에서 시작해, 최대10bytes를 filex에 write한다. - File positiond은 10만큼 움직인다.
- 실제로 기록한 바이트 수만큼 반환된다.
- 에러가 발생한다면
-1이 return 된다.
파일에 직접적으로 string을 write 할 수 있다.
y = write(x, "hello", 5);
string 형 변수를 통해서도 가능하다.
char buf[10];
strcpy(buf, "hello");
y = write(x, buf, 5);
4. standard input, standard output, standard error
y = read(0, buf, 10); // read 10 bytes from the standard input file (keyboard in default)
// and store them in buf
y = write(1, buf, 10); // write 10 bytes from buf in the standard output file (terminal in default)
y = write(2, buf, 10); // write 10 bytes from buf in the standard error file (terminal in default)
5. manuals for system call
$ man 2 open
$ man 2 read
$ man 2 write
man의 mannual에는 각 시스템 호출에 사용해야 하는 파일에 대한 설명이 나와 있다.
추가적인 예제 및 실습 문제들을 확인하고 싶으시면 아래 링크를 클릭해주세요 :)
GitHub - oneonlee/Computer-Science: Introduction to Computer Science
Introduction to Computer Science. Contribute to oneonlee/Computer-Science development by creating an account on GitHub.
github.com
반응형
'Development > Linux' 카테고리의 다른 글
| [Linux] non-text file 및 wav 파일 다루기 (0) | 2022.04.17 |
|---|---|
| [Linux] 원격 파일 전송 (업로드/다운로드) (0) | 2022.04.17 |
| [Linux] C / C++ 컴파일 및 실행 방법 (gcc, g++) (0) | 2022.04.17 |
| [Linux] VI 기본 사용법 및 명령어 정리 (0) | 2022.04.17 |
| [Linux] Command Classification (명령어 분류) (0) | 2022.04.17 |