How to determine whether a file exists in C, and how to judge a file in C
Method 1: the access function checks whether a folder or file exists.
Function prototype: int access (const char * filename, int mode );
Header file: io. h
Filename: Enter the folder path or file path.
Mode: 0 (F_ OK) only determines whether there is
2 (R_ OK) determine the write permission
4 (W_ OK) determine the read permission
6 (X_ OK) determine the execution permission
This interface is used to determine whether a folder exists. When mode is set to 0 and whether a file exists, mode can be set to 0, 2, 4, or 6. If a user exists or has permissions, the returned value is 0. If the user does not exist or has no permissions, the returned value is-1.
Error Code
The file specified by the EACCESS parameter pathname does not meet the required permissions.
The file to be tested by EROFS is stored in the read-only file system.
The pathname pointer of the EFAULT parameter exceeds the accessible memory space.
The mode Val parameter mode is incorrect.
The pathname parameter of ENAMETOOLONG is too long.
The pathname parameter of ENOTDIR is a directory.
Insufficient ENOMEM core memory
The pathname parameter of ELOOP has too many symbolic connections.
Eio I/O access error.
Note: You must be careful when using access () for user authentication. For example, making an open () empty file after access () may cause system security problems.
Instance:
1 #include <stdio.h> 2 3 #include <io.h> 4 5 int main(void) 6 7 { 8 9 if ( !access("C://windows",0) )10 11 puts("C://windows EXISITS!");12 13 else14 15 puts("C://windows DOESN'T EXISIT!");16 17 return 0;18 19 }
Method 2: Use the fopen function to determine whether a file exists.
Function prototype: FILE * fopen (char * filename, char * type );
Filename: file path
Type: open a file (such as r, w, r +, w +, a, rb, and wb)
It is used to determine whether a file exists and can use r or rb. Otherwise, the file may be automatically created. The returned value is NULL (cannot be opened) and positive (can be opened ).
Note: This method is incorrect because some files exist but may not be readable.