I’m stuck on Stage #MG5.
I have done everything write I think but the test script tests for cat tool in “/usr/bin/” directory which is not possible since I’m on Windows. Is it not possible to pass this in Windows? Please provide me some solutions to pass this if possible. I have added my code below.
Here are my logs:
tester::#MG5] [setup] Files created:
[tester::#MG5] [setup] - /tmp/bee/my_exe (not executable)
[tester::#MG5] [setup] - /tmp/cow/my_exe (not executable)
[tester::#MG5] [setup] - /tmp/pig/my_exe (executable)
[tester::#MG5] Running ./your_program.sh
[your-program] $ type cat
[your-program] cat: not found
[tester::#MG5] ^ Line does not match expected value.
[tester::#MG5] Expected: "cat is /usr/bin/cat"
[tester::#MG5] Received: "cat: not found"
[your-program] $
[tester::#MG5] Test failed
And here’s a snippet of my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void check_executable(const char *arg) {
// Fetching the PATH environment variable
char *path_env = getenv("PATH");
if(path_env == NULL) {
printf("%s : not found\n", arg);
return;
}
// coping the address to the PATH variable to be able to tokenize it
char *path_copy = strdup(path_env);
if(path_copy == NULL) {
printf("Memory allocation failed\n");
return;
}
// Tokenizing each directory in PATH
char *dir= strtok(path_copy, ";");
// Iterating through each directory
while(dir != NULL) {
size_t len= strlen(dir) + strlen(arg) + 2;
char *full_path= malloc(len);
if(full_path == NULL) {
printf("Malloc failed!\n");
free(path_copy);
return;
}
snprintf(full_path, len, "%s/%s", dir, arg); // constructing the full path
if(access(full_path, X_OK) == 0) { // check if the file exists AND has execute permission
printf("%s is %s\n", arg, full_path);
free(path_copy);
free(full_path);
return;
}
free(full_path);
dir= strtok(NULL, ";");
}
free(path_copy);
printf("%s: not found\n",arg);
}
int main(int argc, char *argv[])
{
// Flush after every printf
setbuf(stdout, NULL);
//char *path_env = getenv("PATH");
//printf("%s\n", path_env);
while (1)
{
// TODO: Uncomment the code below to pass the first stage
printf("$ ");
char input[50];
fgets(input, sizeof(input), stdin);
input[strlen(input) - 1] = '\0'; // Remove the trailing newline character
// Exit the shell if the user types "exit"
if (strcmp(input, "exit") == 0)
{
break;
}
// Handle the "echo" command
else if (strncmp(input, "echo", 4) == 0)
{
printf("%s\n", input + 5); // Print the string after "echo "
}
// Handle the "type" command
else if (strncmp(input, "type", 4) == 0)
{
if (strcmp(input + 5, "echo") == 0)
{
printf("echo is a shell builtin\n");
}
else if (strcmp(input + 5, "type") == 0)
{
printf("type is a shell builtin\n");
}
else if (strcmp(input + 5, "exit") == 0)
{
printf("exit is a shell builtin\n");
}
else
{
check_executable(input + 5);
}
}
else
{
printf("%s: command not found\n", input);
}
}
return 0;
}