C에 파일이 있는지 확인하는 가장 좋은 방법은 무엇입니까?
단순히 파일을 여는 것보다 더 좋은 방법이 있을까요?
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
검색하다access()
함수, 발견unistd.h
. 기능을 다음과 같이 대체할 수 있습니다.
if( access( fname, F_OK ) == 0 ) {
// file exists
} else {
// file doesn't exist
}
Windows(VC)에서unistd.h
는 존재하지 않습니다.기능시키려면 , 다음의 정의를 실시할 필요가 있습니다.
#ifdef WIN32
#include <io.h>
#define F_OK 0
#define access _access
#endif
를 사용할 수도 있습니다.R_OK
,W_OK
,그리고.X_OK
대신해서F_OK
읽기 권한, 쓰기 권한 및 실행 권한(각각)을 검사하고, 사용자가 또는 둘 중 하나를 함께 사용할 수 있습니다(즉, 다음을 사용하여 읽기 권한과 쓰기 권한 모두 확인).R_OK|W_OK
)
업데이트: Windows 에서는 를 사용할 수 없습니다.W_OK
액세스 함수는 DACL을 고려하지 않기 때문에 쓰기 허가를 확실하게 테스트합니다. access( fname, W_OK )
파일에는 읽기 전용 속성이 설정되어 있지 않기 때문에0(성공)을 반환할 수 있습니다만, 아직 파일에 쓸 수 있는 권한이 없는 경우가 있습니다.
사용하다stat
다음과 같습니다.
#include <sys/stat.h> // stat
#include <stdbool.h> // bool type
bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
이렇게 불러주세요.
#include <stdio.h> // printf
int main(int ac, char **av) {
if (ac != 2)
return 1;
if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);
return 0;
}
일반적으로 파일이 존재하는지 여부를 확인하려는 경우 파일이 존재하지 않는 경우 해당 파일을 생성하려고 하기 때문입니다.Graeme Perrow의 답변은 그 파일을 만들고 싶지 않은 경우에는 좋은 답변이지만, 작성하면 레이스 조건에 취약합니다.다른 프로세스에서는 파일이 존재하는지 여부를 체크하고 실제로 파일을 열어 기입합니다.(웃음)작성된 파일이 심볼링크일 경우 보안에 악영향을 미칠 수 있습니다.)
존재 여부를 확인하고 파일이 존재하지 않는 경우 레이스 조건이 발생하지 않도록 아토믹하게 작성하려면 다음을 사용합니다.
#include <fcntl.h>
#include <errno.h>
fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
/* failure */
if (errno == EEXIST) {
/* the file already existed */
...
}
} else {
/* now you can use the file */
}
네. 사용stat()
man 페이지를stat(2)
참조해 주세요.
stat()
파일이 없으면 실패합니다.그렇지 않으면 성공할 가능성이 높습니다.존재하지만 존재하는 디렉토리에 대한 읽기 액세스 권한이 없는 경우에도 실패하지만, 이 경우 어떤 메서드도 실패합니다(접근 권한에 따라 표시되지 않을 수 있는 디렉토리의 내용을 어떻게 검사할 수 있습니까?).간단하게는 할 수 없습니다).
아, 다른 분께서 말씀하셨듯이access()
. 하지만 나는stat()
파일이 존재하는 것처럼 즉시 많은 유용한 정보를 얻을 수 있습니다(마지막으로 갱신된 날짜, 파일의 크기, 파일을 소유한 소유자 및/또는 그룹, 접근 권한 등).
FILE *file;
if((file = fopen("sample.txt","r"))!=NULL)
{
// file exists
fclose(file);
}
else
{
//File not found, no memory leak since 'file' == NULL
//fclose(file) would cause an error
}
realpath() 함수를 사용할 수 있습니다.
resolved_file = realpath(file_path, NULL);
if (!resolved_keyfile) {
/*File dosn't exists*/
perror(keyfile);
return -1;
}
access() 함수는 다음 중 하나라고 생각합니다.unistd.h
에 있어서 좋은 선택이다Linux
(stat도 사용할 수 있습니다).
다음과 같이 사용할 수 있습니다.
#include <stdio.h>
#include <stdlib.h>
#include<unistd.h>
void fileCheck(const char *fileName);
int main (void) {
char *fileName = "/etc/sudoers";
fileCheck(fileName);
return 0;
}
void fileCheck(const char *fileName){
if(!access(fileName, F_OK )){
printf("The File %s\t was Found\n",fileName);
}else{
printf("The File %s\t not Found\n",fileName);
}
if(!access(fileName, R_OK )){
printf("The File %s\t can be read\n",fileName);
}else{
printf("The File %s\t cannot be read\n",fileName);
}
if(!access( fileName, W_OK )){
printf("The File %s\t it can be Edited\n",fileName);
}else{
printf("The File %s\t it cannot be Edited\n",fileName);
}
if(!access( fileName, X_OK )){
printf("The File %s\t is an Executable\n",fileName);
}else{
printf("The File %s\t is not an Executable\n",fileName);
}
}
다음과 같은 출력이 표시됩니다.
The File /etc/sudoers was Found
The File /etc/sudoers cannot be read
The File /etc/sudoers it cannot be Edited
The File /etc/sudoers is not an Executable
Visual C++ 도움말에서 다음 명령을 사용합니다.
/* ACCESS.C: This example uses _access to check the
* file named "ACCESS.C" to see if it exists and if
* writing is allowed.
*/
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
/* Check for existence */
if( (_access( "ACCESS.C", 0 )) != -1 )
{
printf( "File ACCESS.C exists\n" );
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
printf( "File ACCESS.C has write permission\n" );
}
}
가 있습니다._access(const char *path,
int mode
)
:
00: 존재만
02: 쓰기 권한
04: 읽기 권한
06: 읽기 및 쓰기 권한
의 ★★★★★★★★★★★★★★★★★★★★★로서fopen
파일이 존재하지만 요청대로 열지 못한 경우 오류가 발생할 수 있습니다.
i : Mecki 。 stat()
hum., Ho hum.,
언급URL : https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c
'IT이야기' 카테고리의 다른 글
하드 부동 소수점 숫자와 소프트 부동 소수점 숫자의 차이점은 무엇입니까? (0) | 2022.06.11 |
---|---|
vuex 스토어의 개체에서 값 복사본을 반환하려면 어떻게 해야 합니까? (0) | 2022.06.11 |
printf를 통해 보완이 다르게 동작하는 이유는 무엇입니까? (0) | 2022.06.11 |
다른 메서드에서 정의된 내부 클래스 내의 비최종 변수를 참조할 수 없습니다. (0) | 2022.06.11 |
char*와 const char*의 차이점 (0) | 2022.06.11 |