i am new to C programming and I am making a utility called word-count or wc from scratch.
i am using a command line argument in bash terminal like this:
./wc_app -c -l -w -n ex/foo.txt ex/bar.txt
-c -> for character count
-l -> line count
-w -> word count
-n -> number count
i am reading two files(input- foo.txt and bar.txt) and writing to a output file. in this format:
ex/foo.txt: 125 12 29 13
ex/bar.txt: 125 12 29 13
FOO.txt:
qwe 12 rtyu 34 iop
asdf 5 ghjkl6
7 zxc 8vbnm
90
BAR.txt:
Iro ha nihoheto
Chirinuru wo
Wa ka yo tare so
Tsune naramu
Uwi no okuyama
Kefu koete
Asaki yume mishi
Wehi mo sesu
here is my pseudocode:
- Process command line flags using getopt.
- Loop over the filename arguments
- Open the indicated file (with any error handling)
- Loop over the lines of the file
- Adjust your count of lines and characters.
- Count words
- Count numbers
- Print the file’s results (properly formatted)
- Close the input file
- Print totals
- Close the output file
WC_APP:
Code:
#include"main.h"
#include<stdlib.h>
// this is a sort of "from-scratch challenge"
// instructions on what the program should do are on the site
// (specifics are a way too involved for a pre-function comment, sorry. -蛇)
int main(int argc, char **argv)
{
int opt;
char *line_buf = NULL;
size_t line_buf_size = 0;
ssize_t line_size_fp;
int line_count = 0;
int chars_total = 0;
int word_count = 0;
int integer_count = 0;
while ((opt = getopt(argc, argv, "cwnlo:f:")) != -1) //proccess comand line flags
{
for (int i = 5; i < argc; i++) //Loop over the filename arguments ./wc_lite_app -c -l -w -n ex/foo.txt ex/bar.txt
{
FILE *file_fp = fopen(argv, "r");
if ((file_fp == NULL)) {
fprintf(stderr, "%s: No such file or directory\n", argv);
return 0;
} else {
line_size_fp = getline(&line_buf, &line_buf_size, file_fp);
char *token = strtok(line_buf, " ");
while (line_size_fp >= 0) {
switch (opt) {
case 'c':
// printf("%s\n", line_buf);
if () {
line_size_fp = getline(&line_buf, &line_buf_size, file_fp);
chars_total += line_size_fp;
} else if (argv == 6) {
line_size_fp = getline(&line_buf, &line_buf_size, file_fp);
chars_total += line_size_fp;
}
break;
case 'w':
line_size_fp = getline(&line_buf, &line_buf_size, file_fp);
token = strtok(line_buf, " ");
while (token != NULL) {
// printf("%s\n", token);
token = strtok(NULL, " \n");
word_count++;
}
break;
case 'n':
line_size_fp = getline(&line_buf, &line_buf_size, file_fp);
token = strtok(line_buf, "1234567890");
while (token != NULL) {
// printf("%s\n", token);
token = strtok(NULL, "1234567890");
integer_count++;
}
break;
case 'l':
line_count++;
line_size_fp = getline(&line_buf, &line_buf_size, file_fp);
break;
default:
break;
}
}
}
}
}
printf("%s: %5d %5d %5d %5d\n", argv[5], chars_total, line_count, word_count,
integer_count);
printf("%s: %5d %5d %5d %5d\n", argv[6], chars_total, line_count, word_count,
integer_count);
}