mercredi 1 avril 2015

Nested loop strtok_r issue in C by seperating with ';' and ' '

I want to execute multiple commands like ./shell ls > test.txt;ls > test1.txt;ls > test2.txt; which should print the output 3 times in mentioned files. However, somehow my code only prints once.


I have seperated char buffer by ';' using strtok_r.


Also, I had a look the other example which is similar to my problem. Nested strtok function problem in C


This is my code



int main(int argc,char *argv[])
{
if(argc>1)
{
/*it will check whether a user has entered exit then the code wil be executed successfully.*/
if(strcmp( argv[1], "exit")==0)
{

exit(EXIT_SUCCESS);

}


}

else
{

printf("Enter Shell Command -- ");
char buffer[80];

fgets(buffer, sizeof(buffer), stdin);
//it will replace the newline character with null
buffer[strlen(buffer) - 1] = '\0';

char *end_str;

char* token= strtok_r(buffer, ";", &end_str);





/* string will be splited in individual argument array */
while(token != NULL)
{

int i;
char *endtoken;
printf("a = %s\n", token);
char *array[strlen(buffer)];
i = 0;
char *token2 = strtok_r(token," ", &endtoken);
while (token2 != NULL)
{
array[i++] = token2;
token2 = strtok_r(NULL, " ", &endtoken);
}

if(sizeof(array)>16)
{
char *arrow=array[strlen(buffer)-1];
char *filename;
filename=array[strlen(buffer)];
/*printf("%s",arrow);
printf("%s",filename);*/
if(strcmp( arrow, ">") == 0)
{
freopen( filename, "w", stdout );
}
else if(strcmp( arrow, "<") == 0)
{
freopen( filename, "rb", stdin );
}


}
splittoarray(buffer,argv);

call_system(argv,argc);
token = strtok_r(NULL, ";",&end_str);

}


}
}

Aucun commentaire:

Enregistrer un commentaire