예제 보고 대충 따라서 만들어 봄
stdio.h를 했더니 fopen이랑 추천해주고 있어서 부랴부랴 찾아보니 unistd.h를 쓰라네?
cp.c:18:9: warning: implicit declaration of function ‘read’; did you mean ‘fread’? [-Wimplicit-function-declaration] len = read(fd_src, buff, BUFF_LEN); ^~~~ fread cp.c:20:4: warning: implicit declaration of function ‘write’; did you mean ‘fwrite’? [-Wimplicit-function-declaration] write(fd_dst, buff, len); ^~~~~ fwrite cp.c:25:2: warning: implicit declaration of function ‘close’; did you mean ‘pclose’? [-Wimplicit-function-declaration] close(fd_src); ^~~~~ pclose |
예외처리 하나도 없이 인자만 받아서 복사하는 cp 명령의 마이너 버전 코드.
#include <unistd.h>
#include <fcntl.h>
#define BUFF_LEN 4096
int main(int argc, char** argv)
{
int fd_src = 0;
int fd_dst = 0;
int len = 0;
char buff[BUFF_LEN];
fd_src = open(argv[1], O_RDONLY);
fd_dst = open(argv[2], O_CREAT | O_TRUNC | O_RDWR);
while(1)
{
len = read(fd_src, buff, BUFF_LEN);
if(len > 0)
write(fd_dst, buff, len);
else
break;
}
close(fd_src);
close(fd_dst);
}
[링크 : https://reakwon.tistory.com/39]
[링크 : https://linux.die.net/man/3/open]
[링크 : https://linux.die.net/man/2/close]
fstat으로 파일 길이 알아내기
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFF_LEN 4096
int main(int argc, char** argv)
{
int fd_src = 0;
int fd_dst = 0;
int len = 0;
char buff[BUFF_LEN];
struct stat statbuf;
fd_src = open(argv[1], O_RDONLY);
fd_dst = open(argv[2], O_CREAT | O_TRUNC | O_RDWR);
fstat(fd_src, &statbuf);
printf("filename : [%s], length [%ld]\n", argv[1], statbuf.st_size);
while(1)
{
len = read(fd_src, buff, BUFF_LEN);
if(len > 0)
write(fd_dst, buff, len);
else
break;
}
close(fd_src);
close(fd_dst);
}
'Linux API > linux' 카테고리의 다른 글
linux open() 과 8진법 (0) | 2020.09.28 |
---|---|
open with O_CREAT or O_TMPFILE in second argument needs 3 arguments (0) | 2020.09.28 |
fopen64 (0) | 2019.06.24 |
ubuntu iio rotate key 찾기 또 실패 (0) | 2019.05.27 |
전원버튼 IRQ 발생 관련 (0) | 2018.04.23 |