Hello friends............

How to check whether the given file path is valid or not in C,independent of OS.........
Please reply immediately.........
Thank you.........

Recommended Answers

All 8 Replies

access() in <io.h> can be used to check for path/file existence.

if (access(xxxxx,0) == 0)
{
// perform your objective
}

>How to check whether the given file path is valid or not in C
Don't bother. The OS already implements this behavior, so why add a redundant (and likely inferior) step? Simply pass the path to the appropriate library function and it will get validated somewhere along the line.

>independent of OS.........
fopen.

The only standard way to validate file path is: try to open the file.

int isFilePath(const char* fname) {
    int ok = 0;
    FILE* f;
    if (fname && (f=fopen(fname,"r") != 0) {
        fclose(f);
        ok = 1;
    }
    return ok;
}

Regrettably there are lots of cases when open request failed for the valid path (share or access rights conflict, for example)...

Or, if you want it short:

IsPathValid(const char *fname)
{
    return (!(FILE *f=fopen(fname,"r")))?1:0;
}

It's impossible to declare variables in this context. Try to compile your "short solution"...
and never forget to close opened files ;)...

The stat() or _stat() function will also validate the existance of a file and will return some information about the file

As far as I know _stat is a System V world function. The sys/stat.h header is not standard too...

As far as I know _stat is a System V world function. The sys/stat.h header is not standard too...

You are right about it not being standard C header file -- I had used in in both *nix, unix, MS-DOS, and MS-Windows and just assumed it was standard.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.