-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiles.cpp
More file actions
55 lines (47 loc) · 1.36 KB
/
Copy pathfiles.cpp
File metadata and controls
55 lines (47 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <assert.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include "files.h"
String
read_entire_file(const char* filepath)
{
assert(filepath);
FILE* fp;
fp = fopen(filepath, "r");
if (!fp) {
fprintf(stderr, "Warning: Failed to open file %s\n", filepath);
return 0;
}
fseek(fp, 0, SEEK_END);
u32 filesize = ftell(fp);
rewind(fp);
String result = string_new();
result = string_ensure_fits_len(result, filesize);
u32 bytes_read = fread(result, sizeof(char), filesize, fp);
fclose(fp);
if (bytes_read != filesize) {
fprintf(stderr, "Warning: Failed to read file %s\n", filepath);
string_free(result);
return 0;
} else {
set_string_len(result, filesize);
result[filesize] = '\0';
}
return result;
}
bool is_readable_regfile(const char* path)
{
struct stat file_stat;
// NOTE(christoffer) stat should follow symlinks, which we want
bool is_regfile = (stat(path, &file_stat) == 0 && S_ISREG(file_stat.st_mode));
bool is_readable = access(path, F_OK) != -1;
return is_regfile && is_readable;
}
bool is_readable_dir(const char* path)
{
struct stat file_stat;
bool is_dir = (stat(path, &file_stat) == 0 && S_ISDIR(file_stat.st_mode));
bool is_readable = access(path, F_OK) != -1;
return is_dir && is_readable;
}