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