-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcat.c
59 lines (52 loc) · 1.14 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
// cat program
// By Airbus5717 2021 (C)
// MIT License
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
// if program arguments less than 2
if (argc < 2)
{
printf("%s [filename]\n", argv[0]);
return 0;
}
// open file
FILE *file = fopen(argv[1], "rb");
if (!file)
{
printf("err\n");
return 1;
}
// seek to end of file for calculating length
fseek(file, 0, SEEK_END);
// get length
const size_t length = ftell(file);
// rewind to beginning
rewind(file);
// allocate memory for file
char *str = malloc(length + 1);
if (!str)
{
printf("memory allocation failure\n");
fclose(file);
return 1;
}
// put file in memory
if (fread(str, sizeof(char), length, file) != length)
{
printf("error reading file\n");
free(str);
fclose(file);
return 1;
}
// add null-terminating char
str[length] = '\0';
fprintf(stdout, "%s\n", str);
// dump string output
// printf("%s\n", str);
// free and close
free(str);
fclose(file);
return 0;
}