-
Notifications
You must be signed in to change notification settings - Fork 0
/
cat.c
125 lines (96 loc) · 2.34 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <stdlib.h>
#define sz 200
int main(int argc, char **argv)
{
char *flag = argv[1], *args = argv[2];
if (strlen(flag) != 0){
printf("\nError: No flags for this command!\n");
return 0;
}
if (strlen(args) == 0){ //cat
char *line = (char*)malloc(sz * sizeof(char));
while(1){
fgets(line, sz, stdin);
if (strcmp(line, "end\n") == 0)
break;
printf("%s", line);
}
}
else{
int args_ptr = strlen(args) - 1;
while (args[args_ptr] == ' ' || args[args_ptr] == '\n'){ //removing trailing spaces
args_ptr--;
}
args[args_ptr + 1] = '\0';
int file_ptr = 0, n1 = 0;
char **files = (char**)malloc(sz * sizeof(char*));
char *f = strtok(args, ">");
while (f != NULL){
files[file_ptr] = f;
file_ptr++;
n1++;
f = strtok(NULL, ">");
}
for (int i = 0; i < n1; i++){
char *ptr = strtok(files[i], " ");
while (ptr != NULL){
files[i] = ptr;
ptr = strtok(NULL, " ");
}
}
if ((n1 == 0) || (n1 == 1 && args[strlen(args) - 2] == '>')){ //cat > or cat file >
printf("Error: Invalid command!\n");
return 0;
}
if (n1 == 1){
if (args[0] == '>'){ //cat > file
FILE *fp = fopen(files[0], "w");
if (fp == NULL){
printf("\nError: Couldn't create file!\n");
return 0;
}
char *line = (char*)malloc(sz * sizeof(char));
while (1){
fgets(line, sz, stdin);
if (strcmp(line, "end\n") == 0)
break;
fprintf(fp, "%s", line);
}
fclose(fp);
}
else{ //cat file
FILE *fp = fopen(files[0], "r");
if (fp == NULL){
printf("\nError: Couldn't open file!\n");
return 0;
}
char *line = (char*)malloc(sz * sizeof(char));
while (fgets(line, sz, fp) != NULL){
printf("%s", line);
}
fclose(fp);
}
}
else{ //2 files - cat file1 > file2
FILE *f1 = fopen(files[0], "r");
FILE *f2 = fopen(files[1], "w");
if (f1 == NULL || f2 == NULL){
printf("\nFile error!\n");
return 0;
}
char *line = (char*)malloc(sz * sizeof(char));
while (fgets(line, sz, f1) != NULL){
fprintf(f2, "%s", line);
}
fclose(f1);
fclose(f2);
}
}
return 0;
}