0

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.

4

2 回答 2

4

From the fgets man page:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. [...]

You need to strip the end-of-line marker from the string, otherwise you'll end up with a filename that contains it (and most shells/implementations of ls will replace that with a ? by default).

于 2013-04-28T06:14:30.713 回答
0

write a piece of code in c language which solves my below mentioned purpose------

let i have a folder named wild consisting 5 files-- cat,dog,horse,lion,tiger

now using c/java(file handling concept) write a code to rename those file as---

animal cat,animal dog,animal horse,animal lion,animal tiger

于 2013-06-07T06:51:27.393 回答