Проверка существования файла

Файлы / Базовые операции

#include <sys/stat.h>
#include <unistd.h>

const char *fileName = "file.txt";

//the file to look for
FILE *file = fopen(fileName, "w");
if (file != nullptr) {
    fclose(file);
}

//first method (standard C): the file opens for reading
FILE *infile = fopen(fileName, "r");
bool exists1 = infile != nullptr;
if (infile != nullptr) {
    fclose(infile);
}
//exists1 is true

//second method (POSIX): stat needs no right to read the file
struct stat buffer;
bool exists2 = stat(fileName, &buffer) == 0;
//exists2 is true

//third method (POSIX): access with F_OK asks about existence only
bool exists3 = access("absent.txt", F_OK) == 0;
//exists3 is false

//stat succeeds for a directory too: S_ISREG asks for a plain file
bool isFile = stat(".", &buffer) == 0 && S_ISREG(buffer.st_mode);
//isFile is false

printf("exists1 is %s\n", exists1 ? "true" : "false");
printf("exists2 is %s\n", exists2 ? "true" : "false");
printf("exists3 is %s\n", exists3 ? "true" : "false");
printf("isFile is %s\n", isFile ? "true" : "false");
remove(fileName);