SITERAW

How to know if a file exists in C

Author Message
Khranial # Posted yesterday
Khranial

Hi

I'd like to know a way to check if a file exists in the current directory in C. Or any directory really.

Something like PHP's file_exists or Python's os.path.exists().

Is it possible to do in C standard? Thx

Ads
Clara # Posted two hours ago
Clara

You can use fopen.

FILE * fp = fopen("file.txt", "rb");

if (fp == NULL) {
/* Can't open "file.txt" => file doesn't exist. */
}
else {
/* File was opened, ergo it exists. */
fclose(fp); // Close the file right after.
}


Don't forget to read the C tutorial, these types of questions are answered in depth. Also you may want to check out the FAQ.

Valter # Posted two hours ago
Valter

I don't like ^

If a file can be opened, it must exist. Ok.

But the reverse isn't always true. It can fail to open for multiple reasons, not least of which user permissions.

A better way would be checking if errno is equal to ENOENT (No entry (no such file or directory)).

Alternatively:

#include <unistd.h>
#include <stdio.h>

int main() {
const char *filename = "file.txt";

if (access(filename, F_OK) == 0) {
printf("File exists.\n");
} else {
printf("File does not exist.\n");
}

return 0;
}


The access function here takes two parameters: path and amode. The F_OK argument checks if the file exists. You can also use R_OK, W_OK, or X_OK to check for read, write, or execute permissions, respectively.

Phoenix # Posted one hour ago
Phoenix

Bruh. Burned.

Clara # Posted one hour ago
Clara

My bad I should of checked before posting. But he did ask how to check if a file exists, not if it doesn't exist :°

Khranial # Posted 7 minutes ago
Khranial

Yes it works now. Thanks for your answers!

Post a reply

Please be kind and courteous in your replies. Don't roast others for no reason.