This repository was archived by the owner on Jun 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.c
More file actions
84 lines (76 loc) · 1.82 KB
/
file.c
File metadata and controls
84 lines (76 loc) · 1.82 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
** file.c for someproject in /home/guina_b/
**
** Made by benoit guina
** Login <guina_b@epitech.net>
**
** Started on Fri Jan 01 00:00:00 2010 benoit guina
** Last update Fri Jan 01 00:00:00 2010 benoit guina
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include "xfuncs.h"
#include "file.h"
static int file_map(t_file *file, int fd)
{
struct stat sb;
if (fstat(fd, &sb) < 0)
{
fprintf(stderr, "could not map %s: stat failure: %s\n", file->name, strerror(errno));
return (-1);
}
file->sz = sb.st_size;
if (!S_ISREG(sb.st_mode))
{
fprintf(stderr, "could not map %s: not a regular file\n", file->name);
return (-1);
}
file->sz = sb.st_size;
errno = 0;
if ((file->data = mmap(0, file->sz, PROT_READ, MAP_SHARED, fd, 0)) != MAP_FAILED)
return (0);
fprintf(stderr, "could not map %s: mmap failure: %s\n", file->name, strerror(errno));
return (-1);
}
int file_load(t_file ***file, char *filename)
{
int fd;
if (!(**file = malloc(sizeof(t_file))))
{
fprintf(stderr, "could not load %s: malloc failure\n", filename);
return (-1);
}
(**file)->next = 0;
(**file)->name = filename;
errno = 0;
if ((fd = open(filename, O_RDONLY)) > 0)
{
if (file_map(**file, fd) == 0)
{
xclose(fd, filename);
*file = &(**file)->next;
return (0);
}
xclose(fd, filename);
}
else
fprintf(stderr, "could not load %s: open failure: %s\n", filename, strerror(errno));
free(**file);
**file = 0;
return (1);
}
void file_free(t_file *file)
{
int e;
e = errno;
if (munmap(file->data, file->sz) == -1)
fprintf(stderr, "munmap error on %s: %s\n", file->name, strerror(errno));
errno = e;
free(file);
}