Repository navigation
Expand file tree
/
Copy pathwcat.c
More file actions
73 lines (60 loc) · 1.33 KB
/
Copy pathwcat.c
File metadata and controls
73 lines (60 loc) · 1.33 KB
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
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MY_LIMIT 16384
bool check_if_elf(FILE *file) {
int size = 5;
char *line = malloc(5);
if (fgets(line, size, file) != NULL) {
if (line[0] == 0x7f && line[1] == 0x45 && line[2] == 0x4c &&
line[3] == 0x46) {
free(line);
return true;
}
}
rewind(file);
free(line);
return false;
}
void read_and_write(FILE *file) {
char *line;
int line_max;
if (LINE_MAX >= MY_LIMIT) {
line_max = MY_LIMIT;
} else {
long limit = sysconf(_SC_LINE_MAX);
line_max = (limit < 0 || limit > MY_LIMIT) ? MY_LIMIT : (int)limit;
}
line = malloc(line_max + 1);
if (line == NULL) {
perror("Memory allocation failled");
exit(1);
}
size_t line_no = 0;
while (fgets(line, line_max + 1, file) != NULL) {
line_no++;
printf("%02zu| %s", line_no, line);
}
free(line);
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("%s file ... ", argv[0]);
}
FILE *fp;
for (int i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
printf("wcat: cannot open file\n");
return EXIT_FAILURE;
}
if (!check_if_elf(fp)) {
read_and_write(fp);
} else {
printf("%s is a binary file\n", argv[i]);
}
}
return EXIT_SUCCESS;
}