summaryrefslogtreecommitdiff
path: root/iohelper.c
diff options
context:
space:
mode:
authorakiyamn2020-09-10 18:13:12 +1000
committerakiyamn2020-09-10 18:13:12 +1000
commit03e396142909f633ddc201e7c948bfc71319a0d2 (patch)
tree816ff170bb70044908fd69e99296cea2922b213b /iohelper.c
parentcc006cf8239efd4f30925a1cefb0e408db3ffe0d (diff)
downloadfit2100_ass1-03e396142909f633ddc201e7c948bfc71319a0d2.tar.gz
fit2100_ass1-03e396142909f633ddc201e7c948bfc71319a0d2.zip
Split into two files1.0.0-rc1
Diffstat (limited to 'iohelper.c')
-rw-r--r--iohelper.c69
1 files changed, 69 insertions, 0 deletions
diff --git a/iohelper.c b/iohelper.c
new file mode 100644
index 0000000..de5ad34
--- /dev/null
+++ b/iohelper.c
@@ -0,0 +1,69 @@
+/*
+ * iohelper.c
+ *
+ * Alexander Occhipinti
+ * Student ID: 29994705
+ * Created: 10 Sep 2020
+ * Last Modified: 10 Sep 2020
+ *
+ * iohelper is a small, simple library containing light wrapper functions to Linux system calls.
+ * The functions in iohelper are similar to what would normally be provided in C's stdio.h library.
+ *
+*/
+
+#include <unistd.h>
+#include <sys/file.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <string.h>
+#include "iohelper.h"
+
+/*
+ * Prints a given string to stdout. Returns nothing.
+*/
+void to_stdout(char *string) {
+ write(1, string, strlen(string));
+}
+
+/*
+ * Prints a given string to stderr. Returns nothing.
+*/
+void to_stderr(char *string) {
+ write(2, string, strlen(string));
+}
+
+/*
+ * Given a file path and open() flags, open a file
+ * Catches openning errors, prints an error to stderr when an error occurs and exits
+ * Returns a file descriptor of the open file. Needs to be closed afterwards.
+*/
+int open_file(char *path, int flags){
+ // Read the input file
+ int fd;
+ if ((fd = open(path, flags, NEW_FILE_PERMS)) < 0){
+ int error = errno;
+ to_stderr(path);
+ to_stderr(" could not be opened: ");
+ to_stderr(strerror(error));
+ to_stderr("\n");
+ // Exit as error 2 if the file exists and can not be overwriten
+ if (errno == EEXIST) exit(2);
+ exit(1); // Exit with 1 otherwise
+ }
+ return fd;
+}
+
+/*
+ * Given a source file descriptor open for reading,
+ * put all of its contents in the destination file descriptor open for writing.
+ *
+ * Useful for transferring data between files or stdin/stdout/stderr
+*/
+void file_into_file(int source_fd, int dest_fd){
+ int bytes_read;
+ char buffer[FILE_BUF_SIZE];
+ while ((bytes_read = read(source_fd, buffer, FILE_BUF_SIZE))) {
+ write(dest_fd, buffer, bytes_read);
+ }
+
+} \ No newline at end of file