I am trying to create a two-dimension array of tokens of linux commands in C. (ie, ls -l | grep f*). The first dimension iterates the commands. The second dimension iterates over the arguments of a given command. Then each command with its argument will be stored in the array, which will be passed to execvp for execution.
For example, Tokens[i][j] will give the j-th token for the i-th command.
My code below doesn't work. Probably because I need to overload the + operator to join each command with its argument, which I have not figured out how to do. but the last cout gives me a segmentation fault
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;
int main () {
string s;
cout << "enter commands: " << endl;
getline(cin,s);
//change string to char* for strtok
char *str=const_cast< char *>(s.c_str());
//char *delim=const_cast< char *>(d.c_str());
const int COMMAND = 5;
const int ARGUM = 5;
string mytokens[COMMAND][ARGUM];
char *commands[10]; // Array to hold a max of 10 commands
char *token = strtok(str, "|"); //tokenize input by separating each token by a | symbol
int i = 0;
char *args[10] = {}; //array tp hold command args
int x, y;
for (x = 0; x < 5; x++){
while (token != NULL)
{
commands[x] = token; // each token will be a command
token = strtok(NULL, " ");
}
for (y = 0; y < 5; y++){
args[0] = strtok(commands[y], " "); // each command will be separated from its argument by a space
int tokenCounter = 0;
while (args[tokenCounter] != NULL)
{
tokenCounter++;
args[tokenCounter] = strtok(NULL, " ");
cout << commands[y] << args[tokenCounter] << endl;
// mytokens[y][tokenCounter] = commands[x] + args[tokenCounter];
}
}
}