I’m doing a lot of iterations in order to simulate the bash command (Homework) .
The code works great , but the problem is that after a few iterations of inputs , the program
starts to have some buffer problems . I suspect it has something to do with all the \n of Enter hits .
For example , the code starts like this :
#define BUFFER 4096
#define RUN_FOREVER 1
#define ERROR_SIGN -1
#define TRUE 1
#define FALSE 0
int main(int argc , char * argv[] )
{
char input[BUFFER];
//Get always a command line from the user.
while(RUN_FOREVER)
{
if (isatty(0))
{
// input is from terminal
// need to put something here
}
char **separatedFormAmpersand ;
int ampersandsCtr = 0, k=0,r=0;
char *stringBeforeAmpersand = NULL;
printf("$ ");
memset(input, '\0', BUFFER);
char ch;
scanf("%[^\n]",input);
scanf("%c",&ch);
if(0 == strcmp(input, "exit"))
break;
//Separate the command according to the "&".
stringBeforeAmpersand = strtok( input, "&");
... // more code (quite a lot , frankly)
Now , if the user hits the following inputs :
ls Debug/ | grep r
ls >> file.jer & ls & ls & ls
ls >> file.jer
one after the other , then the code doesn’t recognize the ls command when I hit input number 3 .
If I enter each input in a single run of the code , everything works perfectly .
Any ideas how to clean the buffer ? maybe fflush ?
Thanks!
flushing stdout would clearly be a good thing to do before you can tell anything from your code.
I assume that your pair of
scanfhas the following goal : one will grab one line, and the second will “skip the \n” character. You could just usegetc()for the later, btw. The wonder is whether scanf() itself will read the\ncharacter for you.In its GNU fashion,
scanf()may prove superior tofgets()here, in that the%a[...]modifier can get you rid of “buffer size” limitations and lets the librarymalloc()a buffer of adequate size for you.Ever thought about invoking your program with strace to track reading of the input ?