1#include <errno.h>
 2
 3#include "include/pw.h"
 4#include "include/pwlib/file.h"
 5#include "include/pwlib/path.h"
 6
 7
 8[[nodiscard]] bool pw_fstat(PwValuePtr file_name, struct stat* statbuf)
 9{
10    PwValue file_name_str = PW_NULL;
11    if (!pw_path_as_string(file_name, &file_name_str)) {
12        return false;
13    }
14    PW_CSTRING(fname, &file_name_str);
15
16    if (stat(fname, statbuf) == -1) {
17        pw_exception(PwErrno(errno), "stat failed: %s", fname);
18        return false;
19    }
20    return true;
21}
22
23[[nodiscard]] bool pw_file_exists(PwValuePtr file_name, bool* exists)
24{
25    struct stat statbuf;
26
27    if (!pw_fstat(file_name, &statbuf)) {
28        PwValue status = pw_get_status();
29        if (pw_is_errno(&status, ENOENT)) {
30            *exists = false;
31            return true;
32        }
33        pw_set_status(&status);
34        return false;
35    }
36    *exists = true;
37    return true;
38}
39
40[[nodiscard]] bool pw_file_size(PwValuePtr file_name, off_t* result)
41{
42    struct stat statbuf;
43
44    if (!pw_fstat(file_name, &statbuf)) {
45        return false;
46    }
47    if ( ! (statbuf.st_mode & S_IFREG)) {
48        pw_set_status(PwStatus(PweNotRegularFile));
49        return false;
50    }
51    *result = statbuf.st_size;
52    return true;
53}