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

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

    FILE *file;
        if((file = fopen("sample.txt","r"))!=NULL)
            {
                // file exists
                fclose(file);
            }
        else
            {
                //File not found, no memory leak since 'file' == NULL
                //fclose(file) would cause an error
            }
    

提交回复
热议问题