System Programming
Lab #4
Bacha
2019. 11. 16. 21:24
- 커맨드 라인에서 아래와 같은 내용을 입력받는다 :
% ./a.out <file-name> - access() 시스템 호출을 이용하여,
- 만약 파일이 존재하면 파일에서 20-byte의 데이터를 읽어서 std-out에 출력한다.
- 만약 존재하지 않으면 파일을 새로 만들어, "hello world"라는 내용을 파일에 write 한다.
- 자기 홈 디렉토리에 lab4 디렉토리를 만든 후 프로그램 파일(access.c)을 보관할 것
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <error.h>
#include <stdio.h>
#include <string.h>
#define SIZE 20
int main(int argc, char* argv[]) {
int fd;
if(argc != 2) printf("usage : a.out <pathname>");
if(access(argv[1], F_OK) == 0) {
char buf[SIZE] = "";
fd = open(argv[1], O_RDONLY);
read(fd, buf, SIZE);
printf("%s\n", buf);
}
else {
fd = open(argv[1], O_RDWR|O_CREAT, 0644);
write(fd, "hello world", 12);
}
close(fd);
return 0;
}
컴파일 :
gcc access.c
실행 :
./a.out <file-name(ex. myfile)>