C_C++/C_라이브러리_함수

(C언어) close: 파일을 닫는다

고니자니 2023. 2. 2. 10:10
반응형

#close #open #write

 

#include <io.h>
int close(int handle);

사용중인 파일을 닫는다.

close 함수는 handle과 관련있는 파일을 닫습니다. 

파일을 성공적으로 닫으면 0, 실패하면 -1을 반환합니다.

 

참고: fclose, open, creat, ..

#include <stdio.h>
#include <string.h>
#include <io.h>
#include <fcntl.h>
int main()
{
	int handle;

	char buffer[] = "abcdefg";

	handle = open("testfile.txt", O_CREAT);
	if (handle > -1)
	{
		write(handle, buffer, strlen(buffer));
		close(handle);
	}
	else
		printf("File open Error.\n");

	return 0;
}

 

 

위 코드를 비주얼스튜디어에서 실행되도록 다시 작성했습니다.

#define _CRT_SECURE_NO_WARNINGS  // Visual Studio
#include <stdio.h>
#include <string.h>
#include <io.h>
#include <fcntl.h>
int main()
{
	int handle;

	char buffer[] = "abcdefg";

	handle = _open("testfile.txt", O_CREAT);
	if (handle > -1)
	{
		_write(handle, buffer, strlen(buffer));
		_close(handle);
	}
	else
		printf("File open Error.\n");

	return 0;
}
반응형