What's the best way to check if a file exists in C?

后端 未结 9 1447
眼角桃花
眼角桃花 2020-11-22 04:34

Is there a better way than simply trying to open the file?

int exists(const char *fname)
{
    FILE *file;
    if ((file = fopen(fname, \"r\")))
    {
               


        
9条回答
  •  梦如初夏
    2020-11-22 05:14

    From the Visual C++ help, I'd tend to go with

    /* ACCESS.C: This example uses _access to check the
     * file named "ACCESS.C" to see if it exists and if
     * writing is allowed.
     */
    
    #include  
    #include  
    #include  
    
    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" );
       }
    }
    

    Also worth noting mode values of _access(const char *path,int mode):

    • 00: Existence only

    • 02: Write permission

    • 04: Read permission

    • 06: Read and write permission

    As your fopen could fail in situations where the file existed but could not be opened as requested.

    Edit: Just read Mecki's post. stat() does look like a neater way to go. Ho hum.

提交回复
热议问题