-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-cat.c
64 lines (55 loc) · 1.44 KB
/
01-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
63
64
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#define BYTES_TO_READ 10
int main(int argc, char **argv) {
// Check if correct amount of args is supplied.
if (argc != 2) {
fprintf(stderr, "Invalid arguments.");
return 1;
}
// Open the file specified in argv.
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
// Variant 1 for reading from file.
/* char read_buf[10]; */
/* int bytes_read = read(fd, read_buf, 10); */
/* while (bytes_read != 0) { */
/* bytes_read = read(fd, read_buf, 10); */
/* write(STDIN_FILENO, read_buf, 10); */
/* } */
// Variant 2 for reading from file.
/* char read_buf[10]; */
/* int bytes_read; */
/* while ((bytes_read = read(fd, read_buf, 10)) != 0) { */
/* write(STDIN_FILENO, read_buf, 10); */
/* } */
// Variant 3 for reading from file.
char read_buf[BYTES_TO_READ];
int bytes_read;
do {
// Read from file.
bytes_read = read(fd, read_buf, BYTES_TO_READ);
if (bytes_read == -1) {
perror("read");
close(fd);
return -1;
}
// Print the number of bytes read.
/* printf("<[%d]>\n", bytes_read); */
// Write to the standard output
if (write(STDIN_FILENO, read_buf, bytes_read) == -1) {
perror("write");
}
} while (bytes_read == BYTES_TO_READ);
/* } while (bytes_read != 0); */
// Close file
if (close(fd) == -1) {
perror("open");
return 1;
}
return 0;
}