Write a program to implement the toy shell. It should display the command prompt “myshell$”. Tokenize the command line and execute the given command by creating the child process. Additionally it should interpret the following commands.
count c filename : To print number of characters in the file.
count w filename : To print number of words in the file.
count l filename : To print number of lines in the file.
count c filename : To print number of characters in the file.
count w filename : To print number of words in the file.
count l filename : To print number of lines in the file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
// Function to count characters in a file
void count_characters(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file) {
perror("fopen");
return;
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fclose(file);
printf("Number of characters: %ld\n", file_size);
}
// Function to count words in a file
void count_words(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file) {
perror("fopen");
return;
}
int count = 0;
char ch;
int in_word = 0;
while ((ch = fgetc(file)) != EOF) {
if (ch == ' ' || ch == '\n' || ch == '\t') {
if (in_word) {
count++;
in_word = 0;
}
} else {
in_word = 1;
}
}
if (in_word) {
count++;
}
fclose(file);
printf("Number of words: %d\n", count);
}
// Function to count lines in a file
void count_lines(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file) {
perror("fopen");
return;
}
int count = 0;
char ch;
while ((ch = fgetc(file)) != EOF) {
if (ch == '\n') {
count++;
}
}
fclose(file);
printf("Number of lines: %d\n", count);
}
int main() {
char input[1024];
while (1) {
// Display the command prompt
printf("myshell$ ");
fflush(stdout);
// Read the input command
if (!fgets(input, sizeof(input), stdin)) {
perror("fgets");
exit(EXIT_FAILURE);
}
// Remove newline character from input
input[strcspn(input, "\n")] = '\0';
// Tokenize the command line
char *token = strtok(input, " ");
if (!token) continue; // No command entered
// Check for 'count' command
if (strcmp(token, "count") == 0) {
token = strtok(NULL, " ");
if (!token) continue; // Missing option
char *option = token;
token = strtok(NULL, " ");
if (!token) continue; // Missing filename
char *filename = token;
if (strcmp(option, "c") == 0) {
count_characters(filename);
} else if (strcmp(option, "w") == 0) {
count_words(filename);
} else if (strcmp(option, "l") == 0) {
count_lines(filename);
} else {
printf("Invalid option. Use 'c' for characters, 'w' for words, or 'l' for lines.\n");
}
} else {
printf("Invalid command. Use 'count' followed by option and filename.\n");
}
}
return 0;
}
0 Comments