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

(C언어) access 함수: 파일 속성, 파일이 존재하는지 확인

고니자니 2023. 1. 27. 11:28
반응형

#access #함수 #파일 #속성 #존재하는지 여부

 

#include <io.h>
int access(const char *filename, int amode);

filename으로 지정된 파일이 존재하는지를 조사하고, 파일이 존재하면 파일의 속성을 검사합니다.

비주얼스튜디어에서는 _access 함수를 사용합니다.

 

amode 인수의 값

amode의 값 설명
6 읽기/쓰기가 가능한지 검사
4 읽기가 가능한지 검사
2 쓰기가 가능한지 검사
1 파일의 실행 여부
0 파일이 존재하는지 검사

amode로 지정된 값이 가능하면 0을 반환하고, 그렇지 않으면 -1을 반환합니다.

 

#include <stdio.h>
#include <io.h>
int main()
{
	char file[] = "c:\\temp\\Alarm01.wav";
	if (_access(file, 0) == 0)  // 파일이 존재하면
	{
		printf("%d\n", _access(file, 6));    // Visual Studio
		printf("%d\n", _access(file, 4));
		printf("%d\n", _access(file, 2));
		// printf("%d\n", _access(file, 1));
	}
	return 0;
}

 

아래 코드는 access 함수를 이용해서 파일이 존재하는지 확인하는 예를 보입것입니다.

#include <stdio.h>
#include <io.h>
int file_exists(char filename[])
{
	return (_access(filename, 0) == 0);   // Visual Studio
}

int main()
{
	char file[] = "c:\\temp\\Alarm01.wav";
	if (file_exists(file))
		printf("파일이 존재합니다.\n");
	else
		printf("파일이 존재하지 않습니다.\n");
	return 0;
}

728x90
반응형