C함수 파일 닫기 close()
open() 함수로 열기한 파일을 사용 중지합니다. open()함수는 fcntl.h 에 정의 되어 있지만 write(), read(), close()는 unistd.h에 정의 되어 있습니다.
- 헤더: unistd.h
- 형태: int close(int fd)
- 인수: int 파일 디스크립터
- 반환: int 0 == 정상적으로 close 되었음
-1 == close 실패
C언어 close() 함수 예제
예제는 open()함수에서 올려진 예제로 test.txt라는 파일이 없으면 파일을 생성하고 파일에 "badayak.com"을 쓰기합니다. 그러나 이미 파일이 있다면 프로그램을 종료합니다.
#include <stdio.h> // printf()
#include <string.h> // strlen()
#include <fcntl.h> // O_WRONLY
#include <unistd.h> // write(), close()
int main()
{
char *temp = "badayak.com\n";
int fd;
if ( 0 < ( fd = open( "./test.txt", O_WRONLY ¦ O_CREAT ¦ O_EXCL, 0644))){
write( fd, temp, strlen( temp));
close( fd);
} else {
printf( "파일 열기에 실패했습니다.\n");
}
return 0;
}
C언어 close() 예제 실행 결과
]$ ./a.out
]$ cat ./test.txt
badayak.com
]$ ./a.out
파일 열기에 실패했습니다.
]$
'컴퓨터 > 프로그래밍' 카테고리의 다른 글
C언어 write 함수 파일 쓰기 (0) | 2020.03.14 |
---|---|
C언어 파일 열기 함수 open() (2) | 2020.03.14 |
C언어 그룹 이름으로 그룹 정보 구하기 함수 getgrnam() (0) | 2020.03.14 |