blob: 7ae3f6cfad5886675688cef2586ae3178d1bd51e (
plain)
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
|
/*
* fileutil.c
*
* Alexander Occhipinti
* Student ID: 29994705
* Created: 3 Sep 2020
* Last Modified: 3 Sep 2020
*
* fileutil is a program which is a utility for files. It combines the functionality of cat cp and mv.
* This program allows you to copy the contents of a given file to stdout or to a another file.
* It also allows you to delete the original (i.e. mv) if you please.
*
*/
#include <unistd.h>
#include <sys/file.h>
#include <stdlib.h>
#include <string.h>
#include "fileutil.h"
#define FILE_BUF_SIZE 1024
/*
* 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));
}
/*
* Prints the contents of a given file (provided a path) to stdout.
* Returns nothing.
*/
void print_file(char *read_path) {
int infile, bytes_read;
// Read the input file
if ((infile = open(read_path, O_RDONLY)) <= 2){
to_stderr(read_path);
to_stderr(" could not be opened for reading.\n");
exit(1); // Exit if an error occurs
}
// Write contents to stdout using a buffer
char buffer[FILE_BUF_SIZE];
while ((bytes_read = read(infile, buffer, FILE_BUF_SIZE))) {
write(1, buffer, bytes_read);
}
close(infile);
}
int main(int argc, char *argv[]) {
if (argc >= 2) {
print_file(argv[1]);
} else {
print_file("logfile.txt");
}
return 0;
}
|