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

后端 未结 9 1297
眼角桃花
眼角桃花 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:06

    Use stat like this:

    #include    // stat
    #include     // bool type
    
    bool file_exists (char *filename) {
      struct stat   buffer;   
      return (stat (filename, &buffer) == 0);
    }
    

    and call it like this:

    #include       // 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;
    }
    

提交回复
热议问题