I am writing a c program that simulates the linux shell.
In order to implement i/o redirection using redirection symbol i.e. the > symbol, i make use of freopen to replace stdout with file specified by the user. If say the command is:
environ > bla.txt
My shell will print out the environment variables into bla.txt file instead of stdout.
However, instead of creating "bla.txt" file, the file created is "bla.txt?".
Can anyone solve the mystery behind the ? appended to the filename?
Here's the code for the i/o redirection only:
char *inFile;
pid_t pid;
int rc;
/* keep reading input until "quit" command or eof of redirected input */
while (!feof(stdin))
{
/* get command line from input */
if (fgets (buf, MAX_BUFFER, stdin )) // read a line
{
inFile = strstr(buf, ">"); // look for redirection arrow > in the command
if(inFile != NULL)
{
pid = fork();
if(pid == 0)
freopen( inFile+2, "w", stdout);
else if(pid == -1)
syserr("fork");
else
waitpid(pid,&rc,0);
}
}
}
I have tried googling the solution but can't find anything. I have also tried looking at other stackoverflow question, but can't find answer.
Thanks.