Inizio trattazione statx
[gapil.git] / sources / InitFile.c
1 /* InitFile.c
2  * 
3  * Copyright (C) 2019 Simone Piccardi
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or (at
8  * your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /****************************************************************
20  *
21  * Routine InitFile
22  * Routine to create file with initial content from a buffer
23  *
24  * Author: Simone Piccardi
25  * Jun. 2019
26  *
27  ****************************************************************/
28 #define _GNU_SOURCE
29 #include <limits.h>      /* system limits constants, types and functions */
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>       /* Definition of AT_* constants */
33 #include <unistd.h>      /* unix standard library */
34 #include <errno.h>       /* error definitions and routines */
35 #include <stdio.h>
36 #include <libgen.h>      /* needed for dirname e basename */
37 #include "Gapil.h"
38 #include "macros.h"
39
40 ssize_t InitFile(int dirfd, const char *file, const char *buf, size_t size) 
41 {
42     int fd, written, res;
43     char path[PATH_MAX];
44    
45     fd = openat(dirfd, ".", O_TMPFILE|O_RDWR, S_IRUSR|S_IWUSR);
46     if (fd < 0) {
47         perror("Cannot get temporary filedescritor");
48         return(fd);
49     }
50     written = FullWrite(fd, buf, size);
51     if (written < 0) {
52         perror("error writing on tmp file");
53         return(res);
54     }
55     snprintf(path, PATH_MAX, "/proc/self/fd/%d", fd);
56     res = linkat(AT_FDCWD, path, dirfd, file, AT_SYMLINK_FOLLOW);
57     if (res < 0) {
58         perror("error linking the file");
59         return(res);
60     } else {
61         return written;
62     }
63 }
64