socket

file write, read (linux gcc)

kyeongjun-dev 2020. 4. 3. 16:29

파일 write

low_read.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)
                error_handling("write() error!");
        close(fd);
        return 0;
}

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

 

결과화면

 

파일 read

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);
        if(fd==-1)
                error_handling("open() error!");
        printf("file descriptor: %d \n", fd);

        if(read(fd, buf, sizeof(buf))==-1)
                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);
}

 

결과화면