C language to determine whether a file exists
Use Function access. The header file is Io. H. prototype:
Int access (const char * filename, int amode );
If the amode parameter is 0, the object existence is checked. If the object exists, 0 is returned. If the object does not exist,-1 is returned.
This function can also check other file attributes:
06 check read/write permissions
04 check read permission
02 check write permission
01 check the execution permission
00 check file existence
The experiment is successful under UNIX and VC.
The advantage is that fopen (..., "R") is not good. When there is no read permission, it will not work.
Even if the file has no read permission, you can determine whether the file exists or not.
If 0 exists,-1 exists.
# Include <stdio. h>
Int main ()
{
Printf ("% d", access ("111", 0 ));
Bytes --------------------------------------------------------------------------------------------
# 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 ");
}
}
Output
File Access. C exists
File Access. C has write permission
Bytes -------------------------------------------------------------------------------------------
# Include <stdio. h>
# Include <Io. h>
Int file_exists (char * filename );
Int main (void)
{
Printf ("Does notexist. fil exist: % s/n ",
File_exists ("notexists. fil ")? "Yes": "no ");
Return 0;
}
Int file_exists (char * filename)
{
Return (access (filename, 0) = 0 );
}