반응형

[리눅스 기반에서 실행]

: 파일 입출력 함수를 소켓 입출력에 사용

 

[윈도우 기반에서 실행]

: 파일 입출력 함수를 소켓을 통한 데이터 송수신 함수와 구분

 

  • Low level File Access: 표준에 상관없이 운영체제가 독립적으로 제공
  • File Descriptor (File Handle): 시스템으로부터 할당받은 file 혹은 socket에 부여된 정수

in Linux

file descriptor 대상
0 표준 입력: standard input
1 표준 출력: standard output
2 표준 에러: standard Error

이러한 표준 입출력 대상은 예외적으로 별도의 생성 과정없이 프로그램이 실행되면 자동으로 할당되는 file descriptor


  • 파일 열기

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

int open(const char* path, int flag);

→ 성공 시 file descriptor, 실패 시 -1 반환

- flag

오픈 모드 의미
O_CREAT 필요하면 파일을 생성
O_TRUNC 기존 데이터 전부 삭제
O_APPEND 기존 데이터 보존하고 뒤에 이어서 저장
O_RDONLY 읽기 전용으로 파일 오픈
O_WRONLY 쓰기 전용으로 파일 오픈
O_RDWR 일기, 쓰기 겸용으로 파일 오픈
  • 파일 닫기

#include <unistd.h>                  // #include <io.h>  in window

int close (int fd);

→ 성공 시 0, 실패 시 -1 반환

  • 파일에 데이터 쓰기

#include <unistd.h>                  // #include <io.h>  in window

size_t write(int fd, const void *buf, size_t nbytes);

→ 성공 시 전달한 바이트 수, 실패 시 -1 반환

  • 파일의데이터 읽기

#include <unistd.h>                  // #include <io.h>  in window

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

→ 성공 시 수신한 바이트 수, 실패 시 -1 반환, 파일의 끝에서 0 반환


[파일에 데이터 저장 예제]

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <io.h>

void err_handling(const char* message)
{
	fputs(message, stderr);
	fputs("\n", stderr);
	printf("erroor: %d", WSAGetLastError());
	exit(1);
}
int main()
{
	int fd;
	char buff[] = "Let's go!\n";
	
	fd = open("data.txt", O_CREAT | O_WRONLY | O_TRUNC);	// 생성, 쓰기, 기존 데이터 제거
	if (fd == -1)
		err_handling("open() error");
	printf("file descriptor: %d\n", fd);

	if (write(fd, buff, sizeof(buff)) == -1)
		err_handling("write() error");

	close(fd);


	return 0;
}

[result]

프로그램 창에는

file descriptor: 3

data.txt 파일에는 "Let's go!" 저장

[파일의 데이터 읽기]

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>

#define BUF_SIZE	100
int main()
{
	int fd;
	char buff[BUF_SIZE];

	fd = open("data.txt", O_RDONLY);
	if (fd == -1)
		err_handling("open() error");
	printf("file descriptor: %d\n", fd);

	if (read(fd, buff, sizeof(buff)) == -1)
		printf("read() error");

	printf("read: %s\n", buff);
	close(fd);

	return 0;
}

 

[result]

프로그램 창에는

file descriptor: 3

read: Let's go!

반응형

+ Recent posts