Development/Linux

[Linux] open, read, write - C/C++ 시스템 호출

oneonlee 2022. 4. 17. 19:29
반응형

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 미만일 것이다.
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에서 시작해서 최대 10 bytes를 읽어 character array buf에 저장한다.
  • 10만큼 읽는다면, File position이 10만큼 움직인다.
  • 파일이 처음 열렸을 때의 file position 0이다.
  • 시스템은 y에 실제로 읽은 바이트 수만큼 반환한다.
  • 만약, 파일을 읽는 도중, 에러가 발생한다면 -1을 반환한다.
  • File position이 파일의 끝까지 도달하면 0을 반환한다.

3. write

y = write(x, buf, 10);
  • 위의 write 함수는 buf의 현재 file position에서 시작해, 최대 10 bytes를 file x에 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

 

반응형