-
Notifications
You must be signed in to change notification settings - Fork 1
/
files.c
71 lines (61 loc) · 1.76 KB
/
files.c
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <dirent.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "datatypes.h"
#include "dir.h"
#include "paths.h"
#define LINELEN 256
// mallocs a line read from file
char *get_line(FILE *f) {
char buffer[LINELEN];
char *line = malloc(LINELEN * sizeof(char));
line[0] = '\0';
// collects chunks of bytes until encounter linebreak
while (fgets(buffer, LINELEN, f) != NULL) {
strcat(line, buffer);
if (strlen(buffer) < LINELEN - 1)
return line;
line = realloc(line, (strlen(line) + LINELEN) * sizeof(char));
}
free(line);
return NULL;
}
// checks if path exists as file: true or dir: false
bool check_exists(char *path, bool file) {
struct stat s;
if (stat(path, &s)) {
return 0;
}
return file ? S_ISREG(s.st_mode) : S_ISDIR(s.st_mode);
}
bool is_a_file(char *path) {
return check_exists(path, true);
}
bool is_a_directory(char *path) {
return check_exists(path, false);
}
// writes to buffer and flushes to file
void write_to_file(FILE *f, char *format, char *line) {
int len = fprintf(f, format, line);
if (!len) {
printf("Something went wrong while writing to the file");
exit(-3);
}
fflush(f);
}
// writes file count of directory with message, write_dir = true writes whole directory
int write_file_count(dir_t *directory, char *message, FILE *checkfile, bool write_dir) {
unsigned long num = count_files_in_dir(directory);
char buffer[11] = {0};
snprintf(buffer, 10, "%lu", num);
write_to_file(checkfile, message, buffer);
if (write_dir)
write_dir_to_file(directory, 0, checkfile);
return num;
}