ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 4. File I/O - library calls(3)
    HW & SW Interface/System Programming 2020. 5. 5. 16:52

    # File offset

    모든 파일은 read/write offset을 가지고 있으며,

    File offset은 해당 파일을 열었을 때 읽거나 쓸 시작 위치를 말한다.

     

    파일을 읽거나 쓸때,

    현재 offset의 위치를 그대로 사용하는 것을 sequential access라 하고,

    offset의 위치를 변경해서 사용하는 것을 random access라 한다.

     

     

    # Random access

    r/w offset을 변경하기위해 제공되는 함수(library calls)는 다음과 같다.

     

    파일의 offset 위치 변경

    int fseek(FILE *stream, long offset, int sopt)

    parameters

    • stream: offset을 변경할 파일의 포인터
    • offset: SEEK options에 따른 offset의 상대거리
    • sopt: SEEK options

     

    SEEK options 의미
    SEEK_SET offset
    SEEK_CUR cur_offset + offset
    SEEK_END EOF + offset

     

    return 

    • 성공 -> 0
    • 실패 -> -1

     

     

    파일의 시작점으로 offset 설정

    void rewind(FILE *stream);
    
    == int fseek(FILE *stream, 0, SEEK_SET);

     

    파일의 현재 offset 반환

    long ftell(FILE *stream);
    
    == int fseek(FILE *stream, 0, SEEK_CUR);

    return 

    • 성공 -> 현재 offset
    • 실패 -> -1

     

     

    # I/O Types

    파일을 읽거나 쓸때 데이터의 형식은 다음 두 가지가 있다.

     

    Unformatted I/O (Binary I/O)

    binary format으로 컴퓨터 입장에서 보기 좋은 형식이다.

    지금까지 살펴본 library calls을 예로 들 수 있다.

    -> fread/ fwrite/ fgets/ fputs ...

     

    Formatted I/O

    text format으로 사람 입장에서 보기 좋은 형식이다.

    우리가 c언어로 작성하는 코드를 예로 들 수 있다.

    -> printf/ fprintf/ sprintf/ scanf/ fscanf/ sscanf ...

     

     

    # File Error

    error check

    //발생한 에러 번호 반환 -> 에러 없으면 return 0
    int ferror(FILE *stream);
    
    //파일의 끝인지 아닌지 확인
    int feof(FILE *stream);
    
    //발생한 에러 삭제
    void clearerr(FILE *steram);

     

    error handling

    에러를 다루기 위해서는 반드시 #include <errno.h>를 해야 한다.

    #include <string.h>
    char *strerror(int errnum); //반환된 에러의 넘버가 어떤 에러인지 알려줌
    
    
    #include <stdio.h>
    void perror(const char *msg) //가장 최근에 발생한 에러 알려줌

    'HW & SW Interface > System Programming' 카테고리의 다른 글

    5. File I/O - system calls(1)  (0) 2020.05.05
    3. File I/O - library calls(2)  (0) 2020.05.05
    2. File I/O - library calls(1)  (0) 2020.05.05
    1. Introduction  (0) 2020.05.04

    댓글

Designed by Tistory.