Reputation: 3
So basically I am writing a program that repeatedly reads lines of input from standard input, splits them up in a char **array. For each line, treat the first element as a full path to a program to be executed. Execute the program, passing the rest of the items on the line as arguments. If the line is empty, do nothing and go to the next line. Repeat until the first element is the string ”exit”.
My problems are:
Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFSIZE 10000
int space;
char** createArray(char *line) {
int len_line = strlen(line);
char **wordArray = NULL;
if(len_line > 1){
char *token = strtok(line, " ");
space = 0;
while (token) {
wordArray = realloc(wordArray, sizeof(char*)*++space);
wordArray[space-1] = token;
token = strtok(NULL, " ");
}
}
return wordArray;
}
int main(int argc, const char* argv[]) {
char line[BUFSIZE];
while (1) {
printf("%s\n", ">");
fgets(line, BUFSIZE, stdin);
char** l = createArray(line);
if (l) {
/*why instaed of zero, when l[0]
/*equals quit, strcmp() returns 10?*/
printf("%d\n", strcmp(l[0], "exit"));
if(strcmp(l[0], "exit")==10) {
exit(0);
}
else if(fork() == 0) {
execv(l[0], l);
printf("%s\n", "Error!");
}
}
}
return 1;
}
Upvotes: 0
Views: 181
Reputation: 2648
Coming to the first issue that you are facing
1. when I input "exit", the strcmp(l[0], "exit") returns 10 instead of 0. Why?
When you type "exit" and press Enter key, the string read by fgets is "exit\n". Comparing "exit" with "exit\n" gives 10. Either you remove the "\n" from the end before comparing or change the comparison method to
if(strcmp(l[0], "exit\n") == 0)
See the corrected code below
int main(int argc, const char* argv[]) {
char line[BUFSIZE];
while (1) {
printf("%s\n", ">");
fgets(line, BUFSIZE, stdin);
int len = strlen(line);
line[len - 1] = 0;
char** l = createArray(line);
if (l) {
/*why instaed of zero, when l[0]
equals quit, strcmp() returns 10?*/
printf("%d\n", strcmp(l[0], "exit"));
if(strcmp(l[0], "exit")==0) {
exit(0);
}
else if(fork() == 0) {
execv(l[0], l);
printf("%s\n", "Error!");
}
}
}
return 1;
}
Regarding the second issue
2. The program got compiled but only works for odd number of arguments. For example, if I input "/bin/echo This is good", it prints "This is good" But if I input "/bin/echo This is very good", it prints "error".
Try with the corrected code given below. It works. This issue doesn't exist anymore.
Upvotes: 0
Reputation: 15229
You forgot that fgets()
also returns a newline character, right?
After reading with fgets()
, eliminate it with this line:
line[strlen(line) - 1] = '\0';
Try again, please!
Upvotes: 1