How to check if a file exists on Windows in C

3 Answers

0 votes
#include <stdio.h> 

int file_exists(const char *filename);

int main(void)
{
    if (file_exists("d:\\data.txt"))
        printf("File exists");
    else
        printf("File does not exist.");
    
    return 0;
}
int file_exists(const char *filename)
{
    FILE *fp;
    
    if ( (fp = fopen(filename, "r")) )
    {
        fclose(fp);
        return 1;
    }
    return 0;
}



/*
run:
  
File exists

*/


answered Mar 15, 2015 by avibootz
0 votes
#include <stdio.h>
#include <unistd.h> 

int main(void)
{
    if( access("d:\\data.txt", F_OK ) != -1 )
        printf("File exists");
    else
        printf("File does not exist.");
    
    return 0;
}

/*
run:
  
File exists

*/


answered Mar 15, 2015 by avibootz
0 votes
#include <stdio.h>
#include <sys/stat.h>
 
int file_exists(const char *filename);
 
int main(void)
{
    if (file_exists("d:\\afilename.txt"))
        printf("File exists");
    else
        printf("File does not exist");
     
    return 0;
}
int file_exists(const char *filename)
{
    struct _stat st;
    
    int result = _stat(filename, &st);
    
    return result == 0;
}
 
 
/*
run:
   
File does not exist
 
*/

 



answered Dec 21, 2015 by avibootz

Related questions

3 answers 366 views
366 views asked Jul 12, 2020 by avibootz
1 answer 439 views
1 answer 347 views
1 answer 246 views
246 views asked May 2, 2022 by avibootz
...