/* * 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 #include #include #include #include #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); } }