Получение свойств файла

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

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

const char *filePath = "/tmp/file.txt";

//the file to look at
FILE *out = fopen(filePath, "w");
if (out != nullptr) {
    fputs("Line 1\nLine 2\n", out);
    fclose(out);
}

//stat is POSIX: size, rights, times
struct stat info;
if (stat(filePath, &info) != 0) {
    perror(filePath);
    exit(EXIT_FAILURE);
}

//file size (the first method)
long long fileSize1 = info.st_size;
//fileSize1 is 14

//file size (the second method, standard C)
long fileSize2 = -1;
FILE *in = fopen(filePath, "rb");
if (in != nullptr) {
    fseek(in, 0, SEEK_END);
    fileSize2 = ftell(in);
    fclose(in);
}
//fileSize2 is 14

//file modification time
time_t timeChanges = info.st_mtime;
bool isFresh = difftime(time(nullptr), timeChanges) < 60;
//isFresh is true: the file was written a moment ago

//st_ctime is the time of the last change of the rights,
//not the creation: POSIX does not keep the creation time

//is readable and writable file
bool isReadable = access(filePath, R_OK) == 0;
bool isWritable = access(filePath, W_OK) == 0;
//isReadable is true, isWritable is true

//file extension
const char *dot = strrchr(filePath, '.');
const char *extension = dot != nullptr ? dot + 1 : "";
//extension is "txt"

//file name and directory
const char *slash = strrchr(filePath, '/');
const char *fileName = slash != nullptr ? slash + 1 : filePath;
//fileName is "file.txt"
int dirLength = slash != nullptr ? (int)(slash - filePath) : 0;
//fileDir is "/tmp"

printf("fileSize1 is %lld\n", fileSize1);
printf("fileSize2 is %ld\n", fileSize2);
printf("isFresh is %s\n", isFresh ? "true" : "false");
printf("isReadable is %s\n", isReadable ? "true" : "false");
printf("isWritable is %s\n", isWritable ? "true" : "false");
printf("extension is %s\n", extension);
printf("fileName is %s\n", fileName);
printf("fileDir is %.*s\n", dirLength, filePath);
remove(filePath);