-
Notifications
You must be signed in to change notification settings - Fork 0
/
cat_1.c
65 lines (51 loc) · 1.78 KB
/
cat_1.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
/*
cat_1.c is the simplest implementation of cat, using only stdio.h
although GCC complains about the exit function stdlib.h is not
present.
This program produces a lot of warnings that are to be silenced
with a compiler flag, like:
gcc cat_1.c -w && ./a.out test1.txt
The program cat_2.c is a version of cat_1 that fixes all the warnings.
cat_1 is as unsafely simple as it can be made to work.
To compare the output of cat_1.c to that of the cat UNIX command you
can diff them like this:
diff <(gcc cat_1.c -w && ./a.out test1.txt test2.txt test3.txt) <(cat test1.txt test2.txt test3.txt)
Used references:
https://www.tecmint.com/13-basic-cat-command-examples-in-linux/
https://www.programmingsimplified.com/c-program-read-file
https://stackoverflow.com/questions/6882336/how-to-disable-warnings-when-compiling-c-code
https://askubuntu.com/questions/229447/how-do-i-diff-the-output-of-two-commands
*/
#include <stdio.h>
#include "common.c"
// prints a file handle using a buffer character
void print_file(FILE *f, char *ch) {
while((ch = fgetc(f)) != EOF) {
printf("%c", ch);
}
}
int main (int argc, char *argv[]) {
int number_of_files = argc - 1;
FILE *files[number_of_files];
char buffer_char;
// FILE *fp;
// fp = fopen(argv[1], "r"); // read mode
// print_file(fp, buffer_char);
// loading all file handles
for(int i=1; i <= number_of_files; i++)
{
files[i] = fopen(argv[i], "r");
if (files[i] == NULL) {
perror("Error while opening file\n");
printf(argv[1]);
printf("\n");
exit(1);
}
}
// print and close all file handles
for(int i = 1; i <= number_of_files; i++) {
print_file(files[i], buffer_char);
fclose(files[i]);
}
return 0;
}