How to check whether files exist or not with C regardless of operating system

Asked 1 years ago, Updated 1 years ago, 77 views

Do I have to write it like this to find out if there is a file or not? Please let me know if there is a shorter way. It's too inefficient to check multiple files because there are more files.

int exists(const char *fname)
{
    FILE *file;
    if (file = fopen(fname, "r"))
    {
        fclose(file);
        return 1;
    }
    return 0;
}

c filesystem creoss-platform

2022-09-21 21:35

1 Answers

Use the access() function in unistd.h to reduce code length

if( access( fname, F_OK ) != -1 ) {
    // When a file is present
} } else {
    // When the file does not exist
}

It's not whether there's a file or not When checking whether read/write/execute is possible, write R_OK/W_OK/X_OK in the F_OK position. R_OK | W_OK You can also put several at once by using or


2022-09-21 21:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.