en.subject.pdf

한국어 PDF 번역본 github

✅ 파일에서 한줄씩 읽어서 반환하는 함수 만들기

File Descriptors

c언어 파일 읽기

1) open

#include <fcntl.h>

int open(const char *pathname, int flag);
int open(const char *pathname, int flag, mode_t mode);

*pathname : 절대경로 or 상대경로 (파일명 or 경로)
반환값 : file descriptor(fd) / 실패시 -1

[flag 종류]
O_RDONLY : 읽기 전용으로 파일 열기
O_WRONLY : 쓰기 전용으로 파일 열기
O_RDWR : 쓰기와 읽기 전용으로 열기

2**) close**

#include <unistd.h>

int close(int fd);

반환값 : 정상 종료시 0 / 실패시 -1

3**) read**

#include <unistd.h>

ssize_t read(int fd, void *buff, size_t nbytes);

*buff : 읽은 데이터를 저장할 공간에 대한 포인터

반환값 : 정상 종료시 읽어온 바이트 수 / 실패시 -1 / 읽을 데이터가 없으면(파일의 끝에서 시도) 0

4**) 파일 읽기 기본 예제**

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 1

int main()
{
	int fd;
	char buf[BUFFER_SIZE + 1];
	int tmp_rd_size = 0;

	fd = open("./text.txt", O_RDONLY);
	if (fd == -1)
		printf("file open error")
	else
	{
		while ((tmp_rd_size = read(fd, buf, BUFFER_SIZE)) > 0)
		{
				printf("%s", buf);
				memset(buf, 0, BUFFER_SIZE);
		}
		close(fd);
	}
	return(0);
}