-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwc.c
executable file
·87 lines (76 loc) · 1.76 KB
/
wc.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
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/*
Simulates the behavior of the 'wc' command in Linux
Count words, lines, and characters in files
*/
int main(int argc, char *argv[])
{
char buffer[1024];
int countword = 0, countchar = 0, countline = 0, in_word = 0;
char c;
if (argc < 2)
{
printf("Usage: %s [-l|-w|-m] <file>\n", argv[0]);
return 1;
}
char option='\0';
int file_index = 1;
if (argc == 3)
{
file_index=2;
if (strcmp(argv[1], "-l") == 0)
option = 'l';
else if (strcmp(argv[1], "-w") == 0)
option = 'w';
else if (strcmp(argv[1], "-m") == 0)
option = 'm';
else
{
printf("Invalid option: %s\n", argv[1]);
return 1;
}
}
FILE *fptr = fopen(argv[file_index], "r");
if (fptr == NULL)
{
perror("Error opening file");
return 1;
}
while ((c = fgetc(fptr)) != EOF)
{
countchar++;
if (c == '\n')
countline++;
if (isspace(c))
in_word = 0;
else if (!in_word)
{
in_word = 1;
countword++;
}
}
// Increment line count if the last character is not a newline
if (countchar > 0 && c != '\n')
{
countline++;
}
switch (option)
{
case 'l':
printf("%d %s\n", countline, argv[file_index]);
break;
case 'w':
printf("%d %s\n", countword, argv[file_index]);
break;
case 'm':
printf("%d %s\n", countchar, argv[file_index]);
break;
default:
printf("%d %d %d %s\n", countline, countword, countchar, argv[file_index]);
break;
}
fclose(fptr);
return 0;
}