-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_cat.c
62 lines (51 loc) · 1011 Bytes
/
my_cat.c
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
/* Read a file and print its contents to terminal. */
#include <stdio.h>
#include <stdlib.h>
// added for 2nd solution:
#include <sys/types.h>
#include <sys/uio.h>
#include <fcntl.h>
void my_cat(char *filename);
int main(int ac, char **av)
{
if(ac >= 2 && av[1] != NULL)
{
for(int i = 1; i < ac; i++)
my_cat(av[i]);
}
return 0;
}
void my_cat(char *filename)
{
FILE* fptr;
char c;
fptr = fopen(filename,"r");
if(fptr == NULL) {
printf("Error!");
exit(1);
}
while((c = fgetc(fptr)) != EOF) {
putchar(c);
}
fclose(fptr);
putchar('\n');
}
/*
*** ALTERNATE VERSION ***
int my_cat(char *arg)
{
char buffer[50 + 1];
int readBytes;
int fd;
if ((fd = open(arg, O_RDONLY)) == -1)
{
printf("Error!");
return -1;
}
while ((readBytes = read(fd, buffer, 1)) > 0)
{
buffer[readBytes] = '\0';
printf("%s", buffer);
}
close(fd);
} */