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

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

    I can't remember where I got this from that I used in my assignment (I usually copy paste the URL where I found it as an easy form of citation) and I cannot decipher what the trailing (file) = 0 is although my best guess is that it is redundancy to set any references to file to 0.

    #define fclose(file)  ((file) ? fclose(file) : 0, (file) = 0)
    

    file if a pointer declared as:

    FILE *file=NULL;
    

提交回复
热议问题