I'm writing a simple shell in C. Part of this shell uses bash commands that need to be split up into an array of characters, so that I can properly execute the commands. As a simple proof of concept, I wanted to make a C program that would check to see if its a word, or a special character (|, &, >, and <).
Here is an example of how it should look:
input a command: cat hello.txt |wc -l
---output---
cat
hello.txt
|
wc
-l
So far, I've gotten every case to work, for example except for one, and that is when I do a special character like in |wc l where a letter is after the special character. Here is what my current output looks like:
input a command: cat hello.txt |wc -l
---output---
cat
hello.txt
|wc
-l
Below is my code, I've tried adding special cases, removing cases, and nothing seems to work correctly. How should I solve this?
#include <stdio.h>
#include <string.h>
#define ALPHABET 1000
#define LESS_THAN 60
#define GREATER_THAN 62
#define AMPERSAND 38
#define PIPE 124
#define WHITESPACE 32
#define NEWLINE 10
#define MYCOPOUT 9999
#define CAPITALS(i) ((i >= 65) && (i <= 90))
#define LOWERS(i) ((i >= 97) && (i <= 122))
#define BACKSLASH(i) i == 47
int classify(int i)
{
if (CAPITALS(i) || LOWERS(i) || BACKSLASH(i))
return ALPHABET;
return i;
}
char isSpecial(int i)
{
return (i == LESS_THAN) ||(i == GREATER_THAN) || (i == AMPERSAND) || (i == PIPE);
}
char isWhiteSpace(int i)
{
return (i == WHITESPACE) || (i == NEWLINE);
}
void PRINT_N_NEW(int c, int last)
{
if (isWhiteSpace(last)) {
printf("%c",c);
} else if(isSpecial(last)) {
printf("\n%c\n",c);
} else {
printf("%c\n", c);
}
last = c;
}
int main(int argc, char** argv)
{
int i;
int last = MYCOPOUT;
while ( (i = getchar()) != EOF){
switch(classify(i)){
case ALPHABET:
printf("%c",i);
last = i;
break;
case LESS_THAN:
PRINT_N_NEW(i,last);
break;
case GREATER_THAN:
PRINT_N_NEW(i,last);
break;
case AMPERSAND:
PRINT_N_NEW(i,last);
break;
case PIPE:
PRINT_N_NEW(i,last);
break;
case WHITESPACE:
printf("\n");
last = i;
break;
case NEWLINE:
printf("\n");
last = i;
break;
default:
printf("%c",i);
last = i;
break;
}
}
return 0;
}
ctype.hisspace()instead ofisWhiteSpace(int i). And this,#define AMPERSAND 38is not needed you just nee#define AMPERSAND '&'