0

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];
                         }
                }

  }
Egan
  • 1
  • 1
  • Where are you getting the commands? I don't see, _eg_ `argv` or `str`, anywhere. What are you trying to do? – Neil Feb 15 '21 at 07:29
  • Looks like you've got the early part of a shell pipe sequence. The parsing of the command. You're probably better off with designing a `struct` to contain all the per element data. See my answer: https://stackoverflow.com/questions/52823093/fd-leak-custom-shell/52825582#52825582 – Craig Estey Feb 15 '21 at 07:37
  • str is at the top, char str[50]; – Egan Feb 15 '21 at 07:37
  • 1
    Aside question: How do you sign out of this website? – Egan Feb 15 '21 at 07:44
  • https://meta.stackoverflow.com/questions/294881/how-does-one-logout-from-stack-overflow – Gnoom Feb 15 '21 at 11:10

0 Answers0