본문 바로가기
TIL (Today I Learned)/컴퓨터 시스템(CS)

[CS] 표준 입출력, File offset & File pointerIO #5

by 둥굴프 2022. 12. 14.
이 포스팅은 한국기술교육대학교 김덕수 교수님의 시스템 프로그래밍 (CSE 232)를 참고하여 작성되었습니다.

 

#1 Handling file offset

#include<stdio.h>

int fseek(FILE *stream,long offset,int whence);
long ftell(FILE *stream);
void rewind(FILE *stream);
int fsetpos(FILE *stream,const fpos_t *pos);
int fgetpos(FILE *stream,fpos_t *pos);

stream

offset : 이동시킬 byte 수 (양수 or 음수)

whence : 기준 위치

SEEK_SET, SEEK_CUR, SEEK_END

pos : offset을 저장할(or 하고 있는) fpos_t 주소

Return : Man page 참조

 

#2 File Pointer ↔️ File Descriptor

#include <stdio.h>
FILE *fdopen(int handle, char *type);

fd : file descriptor

mode : 파일 열기 모드

fd를 열 대와 같은 종류여야 함

Return : File pointer | NULL = fail to open

 

#include <stdio.h>
int fileno(FILE *stream);

stream

Return : File descriptor | -1 = error

 

File Pointer ⬅️ File Descriptor

#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
	FILE *fp;
	int fd;
	char str[BUFSIZ];
	fd = open("hello.txt", O_RDONLY);
	if(fd== -1) {
		perror("open");
		exit(1);
	}
	fp= fdopen(fd, "r");
	fgets(str, BUFSIZ, fp);
	printf("Read : %s\n", str);
	fclose(fp);
	return 0;
}

 

File Pointer ➡️ File Descriptor

 

#include <unistd.h>
#include <fcntl.h
#include <stdlib.h>
#include <stdio.h>
int main(void) {
	FILE *fp;
	int fd, n;
	char str[BUFSIZ];
	fp = fopen("cookbook.txt", "r");
	if(fp== NULL) {
		perror("fopen");
		exit(1);
	}
	fd = fileno(fp);
	printf("fd: %d\n", fd);
	n = read(fd, str, BUFSIZ);
	str[n] = '\0';
	printf("Read : %s\n", str);
	close(fd);
	return0;
}

 

#3 Using a temporal file

#include <stdio.h>
char *tmpnam(char *string);
char *tempnam(const char *dir, const char *pfr);

중복되지 않도록 임시 파일명생성

파일명만 생성, 파일은 직접 열어야 함

 

#include <stdio.h>
FILE *tmpfile(void);

임시 파일 포인터 생성

파일명을 알 필요 없이, w+ 모드로 열린 파일 생성

 

 

Summary,

 

1. Buffered IO

(1) Kernel buffer

(2) User-buffered IO

 

2. Standard IO

(1) File pointer (fp)

(2) Open / Close file / stream

(3) Read / Write stream

(4) File synchronization

(5) Handling file offset

(6) File pointer ↔️ file descriptor

(7) Temporal files

 

 

긴 글 읽어주셔서 감사드립니다.

22.12.14

댓글