-
Notifications
You must be signed in to change notification settings - Fork 0
/
cat.c
73 lines (67 loc) · 1.97 KB
/
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
65
66
67
68
69
70
71
72
//cat command
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <zconf.h>
int main(int argc, char **args){
if(argc==3) {
chdir("/");
chdir(*(args+2));
char *line = NULL;
FILE *fptr;
size_t len = 0;
if ((fptr = fopen(*(args + 1), "r")) == NULL) {
printf("No such file or directory\n");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline is encountered
while (getline(&line, &len, fptr) != -1) {
printf("%s", line);
}
fclose(fptr);
}
else if(argc==4){
if(strcmp(*(args+1),"-n")==0){
chdir("/");
chdir(*(args+3));
char *line = NULL;
FILE *fptr;
size_t len = 0;
if ((fptr = fopen(*(args + 2), "r")) == NULL) {
printf("No such file or directory\n");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline is encountered
int i = 1;
while (getline(&line, &len, fptr) != -1) {
printf("%d %s", i, line);
i++;
}
fclose(fptr);
}
else if(strcmp(*(args+1),"-e")==0){
chdir("/");
chdir(*(args+3));
char *line = NULL;
FILE *fptr;
size_t len = 0;
if ((fptr = fopen(*(args + 2), "r")) == NULL) {
printf("No such file or directory\n");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline is encountered
while (getline(&line, &len, fptr) != -1) {
printf("%s$", line);
}
fclose(fptr);
}
else{
printf("Invalid Command, argument required\n");
}
}
exit(0);
}