capture the "stdin redirected file location string" in c

时间:2015-08-14 22:52:41

标签: c command-line-arguments command-prompt stdin

I am not still sure about the wording in the question, anyway --

I have an executable that takes some values as command line argument and also takes a file from stdin like this:

user@pc:~$./executable 0.12345 0.12345 < some/directory/somefile.txt

now is there any way I can grab the file location some/directory/somefile.txt inside the code ?

what I can do is to modify the code to take the file location as another command line argument, but in that case I need to change a lot of things.

So, it would be better if I could do something like this --

int main(int argc, char **argv)
{
    char cmd_prompt[80];
    char file_location[80];
    grab_command_prompt(cmd_prompt);
    split_and_grab_last_token(cmd_prompt, file_location);
    /* this line below should print: "some/directory/somefile.txt" */
    printf("%s\n", file_location); 
}

is it possible ?

1 个答案:

答案 0 :(得分:1)

No. The shell interprets your commandline and, seeing a < opens the file for reading, does a fork(2) and in the child process, replaces stdin with this filehandle using dup2(2) before actually executing your program.