* 파일 디스크립터

   : 운영체제가 만든 파일 또는 소켓의 지칭을 편히 하기 위하여 부여된 숫자




* 저수준 파일 입출력

① 파일 열기




② 파일 닫기



③ 파일에 데이터 쓰기



* low_open.c

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

void error_handling(char * message);

int main(void) {
        int fd;
        char buf[] = "Let's go!\n";

        fd = open("data.txt", O_CREAT | O_WRONLY | O_TRUNC); // 새로운 파일이 생성되어 쓰기만 가능
        if(fd == -1)
                error_handling("open() error");
        printf("file descriptor : %d \n", fd);

        if(write(fd, buf, sizeof(buf)) == -1) // fd 에 저장된 파일 디스크립터에 해당하는 파일에 buf 에 저장된 데이터 전송
                error_handling("write() error");
        close(fd);
        return 0;
}

void error_handling(char * message) {
        fputs(message, stderr);
        fputc('\n', stderr);
        exit(1);
}

[ksh@localhost 110704]$ ./low_open
file descriptor : 3
[ksh@localhost 110704]$ ls
data.txt  hello_client  hello_client.c  hello_server  hello_server.c  low_open  low_open.c
[ksh@localhost 110704]$ cat data.txt
Let's go!
[ksh@localhost 110704]$


④ 파일에 저장된 데이터 읽기




* low_read.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define BUF_SIZE 100

void error_handling(char * message);

int main(void) {
        int fd;
        char buf[BUF_SIZE];

        fd = open("data.txt", O_RDONLY); // data.txt 를 읽기 전용으로 열기
        if(fd == -1)
                error_handling("open() error");
        printf("file descriptor : %d \n", fd);

        if(read(fd, buf, sizeof(buf)) == -1) // buf 를 읽어 데이터를 저장
                error_handling("read() error");
        printf("file data : %s", buf);
        close(fd);
        return 0;
}

void error_handling(char * message) {
        fputs(message, stderr);
        fputc('\n', stderr);
        exit(1);
}

[ksh@localhost 110704]$ ./low_read
file descriptor : 3
file data : Let's go!
[ksh@localhost 110704]$



* fd_seri.c

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>

int main(void) {
        int fd1, fd2, fd3;

        fd1 = socket(PF_INET, SOCK_STREAM, 0);
        fd2 = open("test.dat", O_CREAT | O_WRONLY | O_TRUNC);
        fd3 = socket(PF_INET, SOCK_DGRAM, 0);

        printf("file descriptor 1 : %d\n", fd1);
        printf("file descriptor 2 : %d\n", fd2);
        printf("file descriptor 3 : %d\n", fd3);

        close(fd1);
        close(fd2);
        close(fd3);
        return 0;
}

[ksh@localhost 110704]$ ./fd_seri
file descriptor 1 : 3
file descriptor 2 : 4
file descriptor 3 : 5
[ksh@localhost 110704]$

'Programming > Socket' 카테고리의 다른 글

전화를 거는 소켓의 구현  (0) 2011.07.04
전화를 받는 소켓의 구현  (0) 2011.07.04

+ Recent posts