typeline +n filename :- To print first n lines in the file.
typeline -a filename :- To print all lines in the file
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_INPUT_SIZE 1024
#define MAX_ARG_SIZE 100
void execute_command(char *command);
void typeline(int argc, char *argv[]);
int main() {
char input[MAX_INPUT_SIZE];
while (1) {
// Display the prompt
printf("myshell$ ");
fflush(stdout);
// Read the command from the user
if (fgets(input, sizeof(input), stdin) == NULL) {
perror("fgets");
exit(EXIT_FAILURE);
}
// Remove newline character from the input
input[strcspn(input, "\n")] = 0;
// Tokenize the command
char *args[MAX_ARG_SIZE];
char *token = strtok(input, " ");
int i = 0;
while (token != NULL && i < MAX_ARG_SIZE - 1) {
args[i++] = token;
token = strtok(NULL, " ");
}
args[i] = NULL; // Null-terminate the array of arguments
if (i == 0) continue; // No command entered
// Special handling for the typeline command
if (strcmp(args[0], "typeline") == 0) {
typeline(i, args);
continue;
}
// Fork and execute the command
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// In the child process
execvp(args[0], args);
perror("execvp"); // execvp returns only on error
exit(EXIT_FAILURE);
} else {
// In the parent process
wait(NULL); // Wait for the child process to complete
}
}
return 0;
}
void typeline(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "Usage:\n");
fprintf(stderr, "typeline +n filename : Print first n lines in the file.\n");
fprintf(stderr, "typeline -a filename : Print all lines in the file.\n");
return;
}
int n;
FILE *file;
char line[256];
if (strcmp(argv[1], "+") == 0 && sscanf(argv[2], "%d", &n) == 1) {
file = fopen(argv[3], "r");
if (file == NULL) {
perror("fopen");
return;
}
for (int i = 0; i < n && fgets(line, sizeof(line), file); i++) {
printf("%s", line);
}
fclose(file);
} else if (strcmp(argv[1], "-a") == 0) {
file = fopen(argv[2], "r");
if (file == NULL) {
perror("fopen");
return;
}
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
} else {
fprintf(stderr, "Invalid arguments for typeline command.\n");
}
}
0 Comments