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

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

    I think that access() function, which is found in unistd.h is a good choice for Linux (you can use stat too).

    You can Use it like this:

    #include 
    #include 
    #include
    
    void fileCheck(const char *fileName);
    
    int main (void) {
        char *fileName = "/etc/sudoers";
    
        fileCheck(fileName);
        return 0;
    }
    
    void fileCheck(const char *fileName){
    
        if(!access(fileName, F_OK )){
            printf("The File %s\t was Found\n",fileName);
        }else{
            printf("The File %s\t not Found\n",fileName);
        }
    
        if(!access(fileName, R_OK )){
            printf("The File %s\t can be read\n",fileName);
        }else{
            printf("The File %s\t cannot be read\n",fileName);
        }
    
        if(!access( fileName, W_OK )){
            printf("The File %s\t it can be Edited\n",fileName);
        }else{
            printf("The File %s\t it cannot be Edited\n",fileName);
        }
    
        if(!access( fileName, X_OK )){
            printf("The File %s\t is an Executable\n",fileName);
        }else{
            printf("The File %s\t is not an Executable\n",fileName);
        }
    }
    

    And you get the following Output:

    The File /etc/sudoers    was Found
    The File /etc/sudoers    cannot be read
    The File /etc/sudoers    it cannot be Edited
    The File /etc/sudoers    is not an Executable
    

提交回复
热议问题