Trattazione di linkat e openat con O_TMPFILE, con programmi di test ed
[gapil.git] / sources / InitFile.c
diff --git a/sources/InitFile.c b/sources/InitFile.c
new file mode 100644 (file)
index 0000000..307442a
--- /dev/null
@@ -0,0 +1,64 @@
+/* InitFile.c
+ * 
+ * Copyright (C) 2019 Simone Piccardi
+ * 
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Routine InitFile
+ * Routine to create file with initial content from a buffer
+ *
+ * Author: Simone Piccardi
+ * Jun. 2019
+ *
+ ****************************************************************/
+#define _GNU_SOURCE
+#include <limits.h>      /* system limits constants, types and functions */
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>       /* Definition of AT_* constants */
+#include <unistd.h>      /* unix standard library */
+#include <errno.h>       /* error definitions and routines */
+#include <stdio.h>
+#include <libgen.h>      /* needed for dirname e basename */
+#include "Gapil.h"
+#include "macros.h"
+
+ssize_t InitFile(int dirfd, const char *file, const char *buf, size_t count) 
+{
+    int fd, res;
+    char path[PATH_MAX];
+   
+    fd = openat(dirfd, ".", O_TMPFILE|O_RDWR, S_IRUSR|S_IWUSR);
+    if (fd < 0) {
+       perror("Cannot get temporary filedescritor");
+       return(fd);
+    }
+    res = FullWrite(fd, buf, count);
+    if (res < 0) {
+       perror("error writing on tmp file");
+       return(res);
+    }
+    snprintf(path, PATH_MAX, "/proc/self/fd/%d", fd);
+    res = linkat(AT_FDCWD, path, dirfd, file, AT_SYMLINK_FOLLOW);
+    if (res < 0) {
+       perror("error writing on tmp file");
+       return(res);
+    } else {
+       return 0;
+    }
+}
+