I wrote a program that takes in a txt file and returns an array of the number of characters, words, and lines. This is basically the wc
command.
I'm trying to implement -l
, -c
, -w
for the user to enter into the command line to specify which ones the user wants to see. If none of -l
, -c
, -w
are given, it prints all of them. If the user types ./wc -l -c -w -l -c -w
then it still only prints it once. After -l
, -c
, -w
the user types in the file name.
An example would be ./wc -l -c -w alice.txt anh.txt
.
This would print lines, characters, and words for both text files.
I'm struggling to think of a way to do this. Here is the code I have that returns the array.
I have an idea something like we loop through all arguments and if it finds either -l
or -c
or -w
it will return 1 for true, add it to a separate array, and use that array to print out what is needed.
int *get_counts(char *filename)
{
FILE *file = fopen(filename, "r");
if (file == NULL)
{
printf("NULL FILE");
exit(1);
}
int c;
bool whitespace = true;
static int arr[3] = {0,0,0};
for(;;)
{
c = fgetc(file);
if (c == EOF)
{
break;
}
else if (c == '\n')
{
arr[0] ;
}
else if (whitespace && !isspace(c))
{
arr[1] ;
whitespace = false;
}
else if (!whitespace && isspace(c))
{
whitespace = true;
}
arr[2] ;
}
fclose(file);
return arr;
}
CodePudding user response:
Here is pseudocode for parsing the arguments:
Initialize flag variables: l, c, w = 0
Loop from i = 1 to argc - 1:
Check value of argv[i]:
When "-l", set l flag to 1
When "-c", set c flag to 1
When "-w", set w flag to 1
Otherwise, break loop
Interpret remaining values from argv as filenames